Java Scanner nextLine 问题,需要额外输入

标签 java

我正在研究java I/O。我的代码有一些问题。 我要打印

[0, 0, 1]
[1, 0, 1]
[0, 0, 1]
[2, 0, 1]
[10, 0, 5]

但需要额外输入。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int tc = sc.nextInt();
    sc.nextLine();
    System.out.println();

    for (int i = 0; i < tc; i++) {
        int line = sc.nextInt();
        sc.nextLine();

        for (int j = 0; j < line; j++) {
            System.out.println(i+""+j);
            int[] st = Arrays.stream(sc.nextLine().split(" "))
                    .mapToInt(Integer::parseInt).toArray();
            System.out.println(Arrays.toString(st));
        }
    }
}

下面是输入和输出。我不知道为什么没有显示 [10, 0, 5] 。如果我按 Enter 键,则会出现 [10, 0, 5]。

Input
2
2
0 0 1
1 0 1
3
0 0 1
2 0 1
10 0 5

Output
[0, 0, 1]
[1, 0, 1]
[0, 0, 1]
[2, 0, 1]
(additional enter)
[10, 0, 5]

最佳答案

阅读java doc对于 nextLine 方法。

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

此 nextLine 调用会阻塞,直到找到行分隔符,即附加输入。

int[] st = Arrays.stream(sc.nextLine().split(" "))
                    .mapToInt(Integer::parseInt).toArray();

关于Java Scanner nextLine 问题,需要额外输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51702985/

相关文章:

java - 为什么 Apache POI OPCPackage close() 方法不会保存/写入内容以打开可写文件?

java - 在循环中动态创建 ImageView

java - 使用同步方法锁定时释放 BufferedReader.readLine()

java - Android MediaPlayer 意外停止播放(尚未最终确定)

java - 在调整小程序大小之前,JFrame 不会显示在 JApplet 中

java - 如何引用另一个类中的对象

java - 在我的应用程序中,我可以进入图库,但在选择图像后,它不会覆盖 "OnActivityResult"方法

java - Spark/Scala - 从 Json 创建 DataFrame 时出错 : java. lang.NoSuchMethodError : org. apache.spark.sql.DataFrameReader.json

java - 保证 DateFormat 的年份字段只有两位数的便携方法

java - 如何控制 GWT 中的执行流程?