gpt4 book ai didi

java - 如何在Java中进行多行输入

转载 作者:行者123 更新时间:2023-11-29 06:48:44 24 4
gpt4 key购买 nike

我正在尝试在 Java 中获取多行用户输入并将这些行拆分为一个数组,我需要这个来为在线裁判解决一个问题。我正在使用 Scanner 来获取输入。我无法确定输入结束。我总是得到一个无限循环,因为我不知道输入的大小(即行数)

用空字符串终止输入(点击回车)仍然是一个无限循环。下面提供了代码。

  public static void main(String[] args) {

ArrayList<String> in = new ArrayList<String>();
Scanner s = new Scanner(System.in);

while (s.hasNextLine() == true){
in.add(s.nextLine());
//infinite loop
}
}

我什至不确定循环第一次执行的原因。我相信 hasNextLine() 第一次应该是假的,因为还没有输入。任何帮助或澄清表示赞赏。

最佳答案

您可以使用空行作为循环断路器:

while (s.hasNextLine()){ //no need for "== true"
String read = s.nextLine();
if(read == null || read.isEmpty()){ //if the line is empty
break; //exit the loop
}
in.add(read);
[...]
}

关于java - 如何在Java中进行多行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56887493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com