我昨晚开始做 CodeAbbey 问题,他们提到使用 stdIn,因为有些输入数据很长,所以复制/粘贴比手动容易得多。我以前从未使用过扫描仪,所以看起来很简单。我让它适用于单行输入,然后我遇到了输入问题:
867955 303061
977729 180367
844485 843725
393481 604154
399571 278744
723807 596408
142116 475355
我假设 nextLine 会读取每对,xxxx yyyyy。我根据 nextLine 是否不为空将代码放入 while 循环中。它运行了,但我得到了奇怪的输出,而且只有在我按回车键几次之后。
package com.secryption;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Input: ");
Scanner scanner = new Scanner(System.in);
String input = "";
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
String[] resultSet = input.split("\\s+");
for(String s : resultSet) {
System.out.println(s);
}
}
}
我想在添加scanner.nextLine()到输入后我可能需要一些东西。我尝试了一个空间,但没有帮助。我尝试了换行符,但这并没有使它变得更好。
这个“应该”将所有数字放在一个数组中,没什么特别的。我的扫描仪缺少什么?
编辑:好吧,@Luiggi Mendoza 是对的。我找到了这个How to terminate Scanner when input is complete?邮政。所以基本上它可以工作,我只是期望它能做一些事情。
最佳答案
问题出在这里:
while(!(scanner.nextLine().isEmpty())) {
input = input + scanner.nextLine();
}
Scanner#nextLine
读取该行并将继续读取。您正在读取两行,并且不存储第一行读取的结果,仅读取并存储第二行的结果。
只需将上面的代码更改为:
StringBuilder sb = new StringBuilder();
while(scanner.hasNextLine()) {
sb.append(scanner.nextLine()).append(" ");
}
关于java - 扫描 nextLine,卡在 while 循环中或在奇怪的时间退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32281012/