[英]Java program for splitting strings with line breaks and stops with no entry not working?
This is the problem I'm trying to solve:这是我要解决的问题:
My code is the following:我的代码如下:
import java.util.Scanner;
public class LineByLine {
public static void main(String[] args) {
while (true) {
Scanner scanner = new Scanner(System.in);
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
}
}
My code is showing as wrong and I'm unsure why.我的代码显示错误,我不确定为什么。 Any explanations?
有什么解释吗?
You should arrange your code like:您应该安排您的代码,如:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String sentence = String.valueOf(scanner.nextLine());
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
if (sentence.equals("")) {
break;
}
}
scanner.close();
}
Also you could use hasNext method instead of while(true)
part:您也可以使用 hasNext 方法而不是
while(true)
部分:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String sentence = scanner.nextLine();
String[] pieces = sentence.split(" ");
for (int i = 0; i < pieces.length; i++) {
System.out.println(pieces[i]);
}
}
scanner.close();
}
You'll need to place:您需要放置:
Scanner scanner = new Scanner(System.in);
outside of the while
loop.在
while
循环之外。
The reason:原因:
You only need to create a single Scanner
object.您只需要创建一个
Scanner
object。 This has to be done before you enter the loop since the instantiation will consume the standard input - this means that after the first iteration of the loop, there will be no standard input left to instantiate the object once again.这必须在进入循环之前完成,因为实例化将消耗标准输入 - 这意味着在循环的第一次迭代之后,将没有标准输入可以再次实例化 object。
You can also think about it more mechanically than that:您也可以比这更机械地考虑它:
If you had a loop that was meant to iterate through numbers, you wouldn't want to be resetting your loop counter each time, right?如果您有一个旨在遍历数字的循环,那么您不会希望每次都重置循环计数器,对吗? Its quite a similar thing in this case.
在这种情况下,它非常相似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.