gpt4 book ai didi

java - 出现 NoSuchElementException 并且我找不到解决方法

转载 作者:行者123 更新时间:2023-12-02 12:05:50 32 4
gpt4 key购买 nike

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

代码如下:

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 行是 ->char Guess = input.next().charAt(0); 行。我花了几个小时试图弄清楚如何解决它,但没有结果。有人知道这个错误吗?

提前谢谢您。

最佳答案

而不是

input.close(); 

使用

input.reset();

关于java - 出现 NoSuchElementException 并且我找不到解决方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46913330/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com