我需要编写一个程序,提示用户输入最多 5 个电影标题。用户按 Enter 键退出输入并部分填充数组。
我已经尝试了这些页面中建议的许多解决方案。要么继续循环,要么出现 boolean/字符串转换错误。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String [] Movie = new String[5];
String title;
int count = 0;
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
if(sc.equals("")) {
break;
}
title = sc.nextLine();
Movie[i] = title;
count++;
}
}
for(int i=0; i < Movie.length; i++) {
System.out.println(Movie[i]);
}
}
我希望程序输入代码,直到用户按 Enter 键,然后查看输入内容的输出。
最佳答案
问题是您将 Scanner
对象与空 String
进行比较,这是错误的 sc.equals("")
。首先将输入读入 String 并检查是否为空
for(int i=0; i < Movie.length; i++) {
System.out.println("Enter up to 5 Movie titles (enter null to exit)");
while (sc.hasNextLine()) {
title = sc.nextLine();
if(title.equals("")) {
break;
}
Movie[i] = title;
count++;
}
}
要打印数组,请使用Arrays.toString
System.out.println(Arrays.toString(Movie));
关于java - 当用户输入 null 时如何退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606825/