gpt4 book ai didi

java - 线程 "main"java.util.NoSuchElementException 中的异常(我对此很陌生)

转载 作者:行者123 更新时间:2023-11-29 05:38:25 25 4
gpt4 key购买 nike

我在使用简单代码时遇到了问题,我到处都看到这个问题,但我似乎找不到适合我的修复程序,然后我又在 3 周前才开始学习 java。

这是我编译运行后的错误

$java -Xmx512M -Xms64M RolePlayingGame
Name your adventurer.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at RolePlayingGame.main(RolePlayingGame.java:11)

这是我的代码。这并不紧急,我可能很快就会在类里面学习它,但我仍然想知道,它不是为了上课或其他任何东西,它只是我的一个宠物项目。这是我的少量代码。

import java.util.Scanner;
public class RolePlayingGame
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
int EnemyHack, EnemySlash, EnemyStab, EnemyBlock, Hack, Slash, Stab, Block, Potion, Health, EnemyHealth, EnemyHealth2, EnemyHealth3, EnemyHealth4, EnemyHealth5, Level;
String Hack2, Slash2, Stab2, Block2, Potion2, Name;

Level = 1;
Health = 20+(Level*5);

System.out.println("Name your adventurer.");
Name = keyboard.next();
System.out.println("Your name is " + Name + " .");


System.out.println("You're passing through a murky forest.");
System.out.println("You've been travelling many days. And you are tired.");
System.out.println("There has been a heavy fog for the past week and it");
System.out.println("has begun to grate on your nerves. Recently however,");
System.out.println("you've noticed the fog lessening. As the fog lessens");
System.out.println("you begin to notice shapes, you slowly draw your sword.");
System.out.println("As you pass through the fog a demon lunges at you.");
System.out.println("You let forth a battlecry and begin to fight.");
System.out.println("The enemies health is " + EnemyHealth + " whereas yours is " + Health + " . Do you want to flee?");




}
}

在我添加了 Level 和 Health 之后,我在编译时也开始遇到新的错误。可能是我正在使用的网站(我正在使用在线编译器,网站在我开始收到错误信息后大约一分钟就关闭了)。

最佳答案

错误在这里:Name = keyboard.next();

你应该使用Name = keyboard.nextLine();

java.util.Scanner.next() 方法从这个扫描器中查找并返回下一个完整的标记。一个完整的 token 之前和之后是一个匹配分隔符模式的输入,默认情况下是一个空格。

您可能需要查看 Scanner class 的文档

您还应该看看 Java naming convention

关于java - 线程 "main"java.util.NoSuchElementException 中的异常(我对此很陌生),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18620166/

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