有一个NoSuchElementException,我无法找到解决方法

时间:2017-10-24 14:34:02

标签: java compiler-errors

我为猜词游戏写了一些代码。它从用户输入中读取一个字符并在一个单词中搜索该字符;根据字符是否在单词中,程序返回并控制一些变量。

以下是代码:

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;       
    }

}

但是当我运行它时,我总是会收到这个错误:

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) 

MakeATry()方法中的第54行是该行 - &gt; char guess = input.next().charAt(0);。我花了几个小时试图弄清楚如何解决它,但没有结果。有没有人对这个错误有任何想法?

提前谢谢。

2 个答案:

答案 0 :(得分:1)

而不是

input.close(); 

使用

input.reset();

答案 1 :(得分:0)

首先,您的程序应该验证用户实际上已经输入了一些输入。这听起来就像扫描仪已经到达输入的末尾(在这种情况下,没有任何东西)并抛出一个异常,因为你仍然需要更多,就像它应该的那样。

this所述,某些IDE不允许用户输入,因此即使输入输入,也可能无法在程序中注册。尝试另一个IDE,甚至手工编译整个东西。