1

我遇到了一个简单代码的问题,我到处都看到了这个问题,但我似乎找不到适合我的解决方法,然后我又在 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 后,我在编译时也开始出现新错误。可能是我正在使用的网站(我使用的是在线编译器,网站在我开始收到错误后大约一分钟就关闭了)。

4

1 回答 1

3

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

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

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

您可能想查看Scanner 类的文档

您还应该看看Java 命名约定

于 2013-09-04T17:41:53.110 回答