java – 在一行中获取多个输入,直到用户按Enter键

我想要做的是:

2 (number of test cases)

4 7 8 15 16 (test case 1)

here will be output, for example will print the max number

7 97 1 2 9 (test case 2)

here is output again

我会在每个测试用例中都有一些语句,直到用户按Enter键.我看到了一些类似的问题,但我尝试过的解决方案都没有用.

这是我最后尝试过的:

Scanner cin = new Scanner(System.in);
int test = Integer.parseInt(cin.nextLine());

for (int k = 0; k < test; k++) {
    while (cin.next() != "\\n") {
        int number = cin.nextInt();
        //do something
    }
    //print output
}

最佳答案 您可以读取整个输入行,然后创建一个新的Scanner来读取此行中的整数:

Scanner cin = new Scanner(System.in);
int test = Integer.parseInt(cin.nextLine());

for (int k = 0; k < test; k++) {
    String line  = cin.nextLine();
    Scanner lineScan = new Scanner(line);
    while (lineScan.hasNextInt()) {
        // print number
        System.out.println(lineScan.nextInt());
    }
    //print output
}
点赞