Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 程序不接受用户的输入_Java - Fatal编程技术网

Java 程序不接受用户的输入

Java 程序不接受用户的输入,java,Java,我运行了这段代码(见下文),希望它能提示用户输入第一位超级英雄的名字。但是,它不是从第一行获取用户的输入,而是立即转到“else”后面的语句。这是控制台: How many superheroes would you like? 3 Who is one of the superheroes? Who is another superhero? a Who is another superhero? b Thank you - 1.68 a - 2.78 b - 5.84 System.o

我运行了这段代码(见下文),希望它能提示用户输入第一位超级英雄的名字。但是,它不是从第一行获取用户的输入,而是立即转到“else”后面的语句。这是控制台:

How many superheroes would you like?
3
Who is one of the superheroes?
Who is another superhero?
a
Who is another superhero?
b
Thank you
 - 1.68
a - 2.78
b - 5.84

System.out.println(“你想要多少超级英雄?”);
int n=input.nextInt();
字符串[]超级=新字符串[n];
对于(int i=0;i
尝试使用
Super[i]=input.next();
而不是
input.nextLine()

正如@achAmháin所说,如果您的输入中有空格分隔的单词,您应该使用:

System.out.println("Who is one of the superheroes?");
input.nextLine();
Super[i] = input.nextLine();

正如achAmháin所评论的,问题在于第一个nextInt没有使用输入缓冲区的新行字符,然后当您放置输入时。nextLine();正在检测缓冲区中的字符,而不是等待新的输入

您可以修复此问题,然后放置:

int n = input.nextInt();
这:

然后按照你的期望工作


已测试。

读取副本。简而言之,将
input.nextLine();
放在
int n=input.nextInt()之后是的,我看到了,删除我的评论导致重复@achAmháin如果超级英雄是美国队长怎么办?只占第一个空格。是的,你是对的。我刚刚考虑了给定的例子。我将编辑我的答案。好的观点。有什么想法吗?
int n = input.nextInt();
input.nextLine();