如何强制扫描仪读取未完成的行

时间:2016-11-27 20:50:38

标签: java java.util.scanner

我的最后一行输入有问题。我不能强制扫描仪从最后一行读取数字,因为它未完成。当我在前一行之后用另外一行复制输入时,没有问题,但我不能在那里有额外的行。

Link to problem

输入示例:

2  
1 1  
9 9  
4   
4 5  
6 5  
2 5  
3 4  

-1  

我已经尝试sc.nextInt()sc.next()sc.nextLine(),但没有任何内容可以到达-1。即使sc.hasNextsc.hasNextInt等也在等待。

while(true)
    {
        line = sc.nextLine();
        try {
            a = Integer.parseInt(line);
        } 
        catch (NumberFormatException e) {
        }

        if(a == -1)
        {
            break;
        }

        rr = new int[a][2];

        for(int i = 0; i < a; i++)
        {
            line = sc.nextLine();
            numbers = line.split(" ");

            try {
                rr[i][0] = Integer.parseInt(numbers[0]);
                rr[i][1] = Integer.parseInt(numbers[1]);
            } 
            catch (NumberFormatException e) {
            }

        }

        b = sc.nextInt();

        sc.nextLine();

        tt = new int[b][2];

        for(int i = 0; i < b; i++)
        {
            line = sc.nextLine();
            numbers = line.split(" ");

            try {
                tt[i][0] = Integer.parseInt(numbers[0]);
                tt[i][1] = Integer.parseInt(numbers[1]);
            } 
            catch (NumberFormatException e) {
            }

        }
        sc.nextLine();

    }

2 个答案:

答案 0 :(得分:1)

while(true) {
    // read the line.. 
    line = sc.nextLine().trim();
    // check if it's a blank line...
    // blank line means new test case.. Take the value of n
    if (line.length() == 0) line = sc.nextLine().trim();

    // now parse the value of n.. If it's -1 then end of input
    a = Integer.parseInt(line);
    if (a==-1) break;

    // rest of your input
}

b这样的值:

b = Integer.parseInt(sc.nextLine().trim());

删除&#39;额外&#39;来自sc.nextLine()下方和while循环底部的b。那个案子在顶部处理。

答案 1 :(得分:0)

在尝试获得-1之前,你可以让一个单独的扫描仪使用分隔符/ n(换行符)并让它删除-1和它之前的最后一行之间的额外中断。然后你可以通过.nextLine()或.nextInt()进行扫描。