I have written some code for a word guessing game. It reads a character from user input and searches that character in a word; depending on whether the character is in the word or not, the program returns and controls some variables.
Here's the code:
import java.util.Random;
import java.util.Scanner;
import java.lang.Character;
public class Game {
private String word;
private int wordNum;
private char[] wordinArr = new char[30];
private char[] wordinDashes = new char[30];
private int lettersFound = 0;
int numOfGuesses=10;
public Game() {
Random random = new Random(); //επιλογή τυχαίας λέξης
wordNum = random.nextInt(120);
//System.out.println("Random Number: "+wordNum);
word = Lexicon.getWord(wordNum);
//System.out.println(word);
}
public void startTheGame() {
do {
wordinArr = word.toCharArray();
System.out.println(wordinArr);
System.out.println(word.length());
for(int i=0;i<word.length();i++)
wordinDashes[i]='-';
System.out.println("The random word is now: ");
System.out.println(wordinDashes);
System.out.println("You have "+numOfGuesses+" guesses left.");
if(MakeATry())
numOfGuesses-=1;
}while(numOfGuesses !=0 && lettersFound!=word.length());
if(lettersFound==word.length())
System.out.println("Congratulations! You guessed the word: "+word);
else {
System.out.println("Unfortunately you didn't find the word. The word was"+word);
System.out.println("Try again to find the next word!");
}
}
public boolean MakeATry() {
Scanner input = new Scanner(System.in);
System.out.println("Your guess: ");
char guess = input.next().charAt(0);
if(Character.isLowerCase(guess)){
char temp = Character.toUpperCase(guess);
guess = temp;
}
for(int i=0;i<word.length();i++) {
if(guess==wordinArr[i]) {
System.out.println("The guess is CORRECT!");
wordinDashes[i]=guess;
input.close();
lettersFound++;
return true;
}
}
input.close();
return false;
}
}
But when I run it, I always get this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Game.MakeATry(Game.java:54)
at Game.startTheGame(Game.java:37)
at Main.main(Main.java:17)
The line 54 in MakeATry()
method is that line ->char guess = input.next().charAt(0);
. I have spent hours trying to figure out how to fix it, but no result. Does anyone has any idea about this error?
Thank you in advance.