java Java在空行后停止阅读
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7664108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java stop reading after empty line
提问by Favolas
I'm doing an school exercise and I can't figure how to do one thing. For what I've read, Scanner is not the best way but since the teacher only uses Scanner this must be done using Scanner.
我正在做学校练习,但我不知道如何做一件事。对于我读过的内容,扫描仪不是最好的方法,但由于老师只使用扫描仪,因此必须使用扫描仪来完成。
This is the problem. The user will input text to an array. This array can go up to 10 lines and the user inputs ends with an empty line.
这就是问题。用户将文本输入到数组中。这个数组最多可以有 10 行,用户输入以空行结束。
I've done this:
我已经这样做了:
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++;
}
But this is not working properly and I can't figure it out. Ideally, if the user enters:
但这不能正常工作,我无法弄清楚。理想情况下,如果用户输入:
This is line one
This is line two
and now press enter, wen printing the array it should give:
现在按回车键,打印它应该给出的数组:
[This is line one, This is line two, null,null,null,null,null,null,null,null,null]
Can you help me?
你能帮助我吗?
回答by Mark Peters
while (!sc.nextLine().equals("")){
text[i] = sc.nextLine();
i++;
}
This reads two lines from your input: one which it compares to the empty string, then another to actually store in the array. You want to put the line in a variable so that you're checking and dealing with the same String
in both cases:
这从您的输入中读取两行:将其与空字符串进行比较,然后将另一行实际存储在数组中。您想将该行放在一个变量中,以便String
在两种情况下检查和处理相同的内容:
while(true) {
String nextLine = sc.nextLine();
if ( nextLine.equals("") ) {
break;
}
text[i] = nextLine;
i++;
}
回答by Matt Ball
Here's the typical readline idiom, applied to your code:
这是应用于您的代码的典型 readline 习惯用法:
String[] text = new String[11]
Scanner sc = new Scanner(System.in);
int i = 0;
String line;
System.out.println("Please insert text:");
while (!(line = sc.nextLine()).equals("")){
text[i] = line;
i++;
}