Java 扫描仪出现NoTouchElementException错误
我对java编程非常陌生,在尝试编写一个游戏时遇到了一些困难。下面是导致错误的方法Java 扫描仪出现NoTouchElementException错误,java,nosuchelementexception,Java,Nosuchelementexception,我对java编程非常陌生,在尝试编写一个游戏时遇到了一些困难。下面是导致错误的方法 public static void dragonNest(Dragon player) { int loop = 0; Scanner input = new Scanner(System.in); Territory dragonLand = new Territory(10, 5); loop = dragonLand.population + loop; int m
public static void dragonNest(Dragon player) {
int loop = 0;
Scanner input = new Scanner(System.in);
Territory dragonLand = new Territory(10, 5);
loop = dragonLand.population + loop;
int menuChoice;
int ventureChoice;
boolean choice = false;
boolean validOption = true;
System.out.println("Welcome to your nest, " + player.dragonName);
while (choice == false) {
System.out.println("What would you like to do?");
System.out.println("Press 1 to view your hoard");
System.out.println("Press 2 to venture forth from your nest");
menuChoice = input.nextInt();
if (input.hasNextInt()) {
if (menuChoice > 5 || menuChoice < 1) {
System.out.println("That is not a valid option");;
}
else if (menuChoice == 1){
System.out.println("Your hoard is worth " + player.dragonHoard + " gold pieces.");
}
else if (menuChoice == 2) {
System.out.println("You fly forth from your den");
System.out.println("Press 1 to raid a nearby village, 2 to expand your territory, and 3 to return to your nest");
ventureChoice = input.nextInt();
do {
if (ventureChoice < 3 || ventureChoice < 1) {
System.out.println("That is not a valid option");
validOption = false;
}
else if (ventureChoice == 1) {
System.out.println("You fly forth to raid a nearby village");
Random generator = new Random();
int dragonPower = player.dragonLevel * 2;
int villageOffense = generator.nextInt() + 20 + dragonPower;
int villageDefense = generator.nextInt() + 20 + dragonPower;
int villageFirepower = generator.nextInt() + 20 + dragonPower;
int villageWealth = generator.nextInt() + 20 + dragonPower;
Village enemy = new Village(villageOffense, villageDefense, villageFirepower, villageWealth);
player = villageCombat(player, enemy);
}
}
while (validOption == false);
}
input.close();
}
}
如果您需要更多的程序代码来解决这个问题,请告诉我。先检查是否有int。替换
menuChoice = input.nextInt();
if (input.hasNextInt()) {...
与
我认为你的问题出现是因为你有投入。关闭;在这里,也可能在其他方法中。如果关闭扫描仪,它将关闭底层可读文件,在这种情况下,System.in在关闭后将无法使用它。在本项目中,您希望使用System.In进行其他输入,因此不要关闭扫描仪这里对您来说,一个好的起点是启用调试并逐步通过代码查找故障。当您询问dragon的颜色时,您可以从行中读取一个数字。为什么不尝试同样的方法呢?我无法在我用来读取颜色的代码和我试图在菜单中使用的代码之间找到有意义的区别。至于调试模式,它似乎证实了我已经相信的:当程序运行以下行时会发生错误:menuChoice=input.nextInt;
menuChoice = input.nextInt();
if (input.hasNextInt()) {...
if (input.hasNextInt()) {
menuChoice = input.nextInt();
...