2016-11-27 34 views
0

最後一行輸入有問題。由於未完成,我無法強制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.hasNext,sc.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(); 

    } 
+1

使用nextLine讀取所有行。解析整數(s)作爲第二步 –

+1

嘗試,不幸的是它沒有工作...可能它等待線結束或什麼 –

+0

試試這個http://stackoverflow.com/questions/5868369/how-to-read-a -large-text-file-line-by-line-using-java should help –

回答

0

試圖讓之前的-1你可以有一個單獨的掃描儀使用的分隔符/ N(換行),並將它刪除-1之前的最後一行的額外休息。然後你可以通過.nextLine()或.nextInt()掃描。

+0

不是這樣嗎? .nextLine()在同一個地方? –

+0

.nextLine()將返回下一行的內容。我建議的是建立一個掃描儀,以便它搜索空行,然後編輯該文件,使其不包含空行。之後,它會通過並得到你想要的整數,並且應該沒有問題-1,因爲它不再有空行將它與其他數字分開。 –

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()); 

而且從下面的b和while循環的底部移除 '額外' sc.nextLine()。該案件在頂部處理。

+0

既不工作也不工作。我試圖調試它,並在if(line.length()== 0)line = sc.nextLine(); –

+0

使用這些網站:http://uhunt.felix-halim.net/id/377362 https://www.udebug.com/UVa/12389我編輯了我的答案。在解析它之前,您可能需要修剪這些字符串。 – rafid059