I have developed a hangman game which is 99% complete. I just have one glitch and the glitch is when the user does not enter in a guess and presses enter.
I know that we cannot check if a character is empty so instead I check if a string is empty using scanner.nextLine().isEmpty()
. Now if I don't enter anything and I press enter then it works fine and outputs the printline message.
However if I enter in a letter and press enter, then it goes to the next line and it wants me to enter in something. If I enter in another letter then it works fine, if I enter in nothing and press enter then I get an exception where
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
So I believe my problem is the if statement where I check for string to be empty and if not then move onto checking the character:
if (scanner.nextLine().isEmpty()) {
System.out.println("Your guess seems empty. Please enter in a letter or number");
} else {
char input = scanner.nextLine().charAt(0);
if (input == '-' || Character.isLetter(input) || Character.isDigit(input)) {
if (input == '-') {
weArePlaying = false;
wordCompleted = true;
}
....
}
How can I jiggle this so that if empty string then ask user to guess again else if not empty then proceed with the guess?
Below is more of the code:
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> movieList = new ArrayList<>();
File file = new File("C:\\Users\\mmkp1\\Documents\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
int attempts = 10;
Scanner scanner = new Scanner(System.in);
Random random = new Random();
ArrayList<Character> guessedLetters = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
// Reads the whole file
movieList.add(line);
}
boolean weArePlaying = true;
while (weArePlaying) {
System.out.println("Welcome to Guess The Movie Game");
int index = random.nextInt(movieList.size());
String getMovies = movieList.get(index);
char[] randomWordToGuess = getMovies.toLowerCase().toCharArray();
int wordLength = randomWordToGuess.length;
char[] playerGuess = new char[wordLength];
boolean wordCompleted = false;
for (int i = 0; i < playerGuess.length; i++) {
playerGuess[i] = '_';
}
for (int i = 0; i < randomWordToGuess.length; i++) {
if (randomWordToGuess[i] == ' ') {
playerGuess[i] = ' ';
}
}
while (!wordCompleted && attempts != 0) {
printArray(playerGuess);
System.out.println("Number of attempts left: " + attempts);
System.out.println("Your previous guesses were:" + guessedLetters);
System.out.println("Enter a letter or number");
if (scanner.nextLine().isEmpty()) {
System.out.println("Your guess seems empty. Please enter in a letter or number");
} else {
char input = scanner.nextLine().charAt(0);
if (input == '-' || Character.isLetter(input) || Character.isDigit(input)) {
if (input == '-') {
weArePlaying = false;
wordCompleted = true;
}
....
}