【发布时间】:2018-09-18 16:11:37
【问题描述】:
我正在制作游戏,目前我需要为“英雄”设置名称!这需要玩家输入英雄的名字。 问题是,当它在控制台中询问英雄 1 的名字时,它只是跳过并直接进入英雄 2。 如果我使用 .next() 而不是 .nextLine(),它可以工作,但它会将任何带有空格的名称解释为两个不同的名称!
这是代码,我希望有意义!提前谢谢大家:)
public void heroNames() //sets the name of heroes
{
int count = 1;
while (count <= numHeroes)
{
System.out.println("Enter a name for hero number " + count);
String name = scanner.nextLine();
if(heroNames.contains(name)) //bug needs to be fixed here - does not wait for user input for first hero name
{
System.out.println("You already have a hero with this name. Please choose another name!");
}
else
{
heroNames.add(name);
count++; //increases count by 1 to move to next hero
}
}
}
【问题讨论】:
-
在循环前添加
scanner.nextLine()。 -
从你的循环中创建名称 String 并将其分配给扫描仪的返回。
标签: java while-loop io java.util.scanner next