I'm trying to get user input in a loop but it crashes on the second iteration of the while. I get input once but it crashes on the second time calling getInput()
, I know for a fact that the first iteration is done fully.
while(!isAnagram(playerLetters,cw.toString())) {
char userChar = getInput(); //crash on the second call
System.out.println(userChar); //for debugging
if(cw.toString().indexOf(userChar) == -1)
System.out.println("Character not in the word, try again");
else {
for(int i = 0; i < cw.numOfOccurrences(userChar); i++)//add the letter to correct guessed letter the number of time it occurs in the word
playerLetters = playerLetters + userChar;
System.out.println("The character is in the word!");
}
System.out.println(userChar); //for debugging
printUI();
trys++;
}
And this is getInput()
:
private char getInput() {
Scanner scan = new Scanner(System.in);
String current = "";
do {
current = scan.next();
if(current.length() > 1)
System.out.println("Please enter only one character");
else if(usedLetters.contains(current.charAt(0)))
System.out.println("This character has already been used");
else if(!Character.isLetter(current.charAt(0)) || !Character.isLowerCase(current.charAt(0))) //Check if input is a lower case letter
System.out.println("Invalid input");
else {
usedLetters.add(current.charAt(0));
break;
}
} while(true);
scan.close();
return current.charAt(0);
}
You can put
Scanner scan = new Scanner(System.in)
outside of getInput method to not call it each iteration in your class
Scanner scan = new Scanner(System.in);
private char getInput() {
String current = "";
do {
current = scan.next();
if(current.length() > 1)
System.out.println("Please enter only one character");
else if(usedLetters.contains(current.charAt(0)))
System.out.println("This character has already been used");
else if(!Character.isLetter(current.charAt(0)) || !Character.isLowerCase(current.charAt(0))) //Check if input is a lower case letter
System.out.println("Invalid input");
else {
usedLetters.add(current.charAt(0));
break;
}
} while(true);
return current.charAt(0);
}
....
// then your loop
while(!isAnagram(playerLetters,cw.toString())) {
char userChar = getInput(); //crash on the second call
System.out.println(userChar); //for debugging
if(cw.toString().indexOf(userChar) == -1)
System.out.println("Character not in the word, try again");
else {
for(int i = 0; i < cw.numOfOccurrences(userChar); i++)//add the letter to correct guessed letter the number of time it occurs in the word
playerLetters = playerLetters + userChar;
System.out.println("The character is in the word!");
}
System.out.println(userChar); //for debugging
printUI();
trys++;
}
// dont forget to close your scanner after the loop
scan.close();