每當我運行這個時,chooseCave()
函數可以正常工作,in.nextInt()
。當我選擇山洞,消息彈出在2秒的時間間隔,然後只要它得到過去的那一部分,它給我的錯誤:線程「main」中的異常java.util.NoSuchElementException
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Dragon.main(Dragon.java:81)
我試圖hasNextLine()
和hasNextInt()
,當我在main
方法中使用while hasNextLine()
,我得到了更多的錯誤。當我在chooseCave()
方法中使用while hasNextInt()
時,它不接受我的輸入。
當我在chooseCave()
方法使用if hasNextInt()
,它不接受我playAgain
字符串輸入,並直接進入另一場比賽,但隨後hasNextInt()
布爾回報false
並修建垃圾「哪個山洞裏......」無限。
我已經通過錯誤報告和Java文檔和堆棧溢出的類似問題。請幫忙。
import java.util.Scanner;
public class Dragon {
public static void displayIntro() {
System.out.println("You are in a land full of dragons. In front of you, ");
System.out.println("You see two caves. In one cave, the dragon is friendly");
System.out.println("and will share his treasure with you. The other dragon");
System.out.println("is greedy and hungry, and will eat you on sight");
System.out.println(' ');
}
public static int chooseCave() {
Scanner in = new Scanner(System.in);
int cave = 0;
while (cave != 1 && cave != 2) {
System.out.println("Which cave will you go into? (1 or 2)");
cave = in.nextInt();
}
in.close();
return cave;
}
public static void checkCave(int chosenCave) {
System.out.println("You approach the cave...");
try
{
// Sleep at least n milliseconds.
// 1 millisecond = 1/1000 of a second.
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("awakened prematurely");
}
System.out.println("It is dark and spooky...");
try
{
// Sleep at least n milliseconds.
// 1 millisecond = 1/1000 of a second.
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("awakened prematurely");
}
System.out.println("A large dragon jumps out in front of you! He opens his jaws and...");
try
{
// Sleep at least n milliseconds.
// 1 millisecond = 1/1000 of a second.
Thread.sleep(2000);
}
catch (InterruptedException e)
{
System.out.println("awakened prematurely");
}
double friendlyCave = Math.ceil(Math.random() * 2);
if (chosenCave == friendlyCave) {
System.out.println("Gives you his treasure!");
}
else {
System.out.println("Gobbles you down in one bite!");
}
}
public static void main(String[] args) {
Scanner inner = new Scanner(System.in);
String playAgain = "yes";
boolean play = true;
while (play) {
displayIntro();
int caveNumber = chooseCave();
checkCave(caveNumber);
System.out.println("Do you want to play again? (yes or no)");
playAgain = inner.nextLine();
if (playAgain == "yes") {
play = true;
}
else {
play = false;
}
}
inner.close();
}
}
+1,我忘了提及一個輸入問題的多個掃描儀。 – syb0rg 2013-03-14 00:37:16
感謝你和syb0rg。我只需要使用掃描儀刪除方法,並在主要方法中放置等效物。有用!在新的編程語言中取得第一次成功......感覺非常好。 :) – 2013-03-15 08:49:07