我正在做一个学校练习,但我不知道如何做一件事。 根据我的阅读,Scanner 并不是最好的方法,但由于老师只使用 Scanner,因此必须使用 Scanner 来完成。
这就是问题所在。 用户将文本输入到数组中。这个数组最多可以有 10 行,用户输入以空行结尾。
我这样做过:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.println("Please insert text:");
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
但这不能正常工作,我无法弄清楚。 理想情况下,如果用户输入:
This is line one
This is line two
现在按回车键,打印它应该给出的数组:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
你能帮帮我吗?
最佳答案
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
这会从您的输入中读取两行:将其中一行与空字符串进行比较,然后将另一行实际存储在数组中。您希望将该行放入变量中,以便在两种情况下检查和处理相同的 String
:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
关于Java 在空行后停止读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7664108/