2012-12-05 117 views
0

我用這個代碼:scanNextInt()忽略空行

public String processFile(Scanner scanner) { 
    String result = ""; 
    SumProcessor a = new SumProcessor(); 
    AverageProcessor b = new AverageProcessor(); 
    String line = null; 
    while (scanner.hasNext()) { 

     if (scanner.hasNext("avg") == true) { 

      c = scanner.next("avg"); 
      while(scanner.hasNextInt()){ 

       int j = scanner.nextInt(); 
       a.processNumber(j); 
      } 
      System.out.println("Exit a"); 
      result += a.getResult(); 
      a.reset(); 
     } 
     if (scanner.hasNext("sum") == true) { 

      c = scanner.next("sum"); 
      while(scanner.hasNextInt()){ 

      int j = scanner.nextInt(); 
       b.processNumber(j);      
      } 
      System.out.println("Exit b"); 
      result += b.getResult(); 
      b.reset(); 
     } 

    } 
    return result; 
} 

,我需要結束while循環(hasNexInt()),當我按下輸入或發送空行。

我嘗試用一​​些方法與字符串== NULL等,但Java的忽略空行

輸出

run: 
avg 
1 
2 
3 
4 

sum 
Exit a 
1 
2 
3 
4 

但我需要:

run: 
avg 
1 
2 
3 
4 

Exit a 
sum  
1 
2 
3 
4 

回答

1

如果您的應用程序掃描儀的使用也不是絕對必須的,我可以提供這樣的:

BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in)); 
for(;;) { 
    String lile = rdr.readLine(); 
    if (lile.trim().isEmpty()) { 
     break; 
    } 
    // process your line 
} 

此代碼絕對的空行停止從控制檯。現在您可以使用掃描儀進行線處理或正則表達式。

1

剛使用類似於:

String line = null; 
while(!(line = keyboard.nextLine()).isEmpty()) { 
// Your actions 
} 
+0

已經嘗試此 – JohnDow

+0

固定碼和控制檯輸出 – JohnDow

0

只需添加scanner.nextLine()忽略該行剩餘的條目:

  while (scanner.hasNextLine()){ 
       String line = scanner.nextLine(); 
       if("".equals(line)){ 
        //exit out of the loop 
        break; 
       } 
       //assuming only one int in each line 
       int j = Integer.parseInt(line); 
       a.processNumber(j); 
      } 
+0

我不需要忽略空行,我需要不能忽略空行 – JohnDow

+0

@ VladislavIl'ushin我的意思是,它會忽略你與nextInt一起輸入換行符( )。我進一步改進了答案,在最後忽略了新行字符之前,從行中讀取所有'int'類型的輸入。 –

+0

固定代碼和控制檯輸出 – JohnDow

1

使用hasNextInt()在你的第二個while循環。當你不通過int值時,while循環將會中斷。

或者你也可以確定一個特定的值,你可以通過打破循環。例如,您可以傳遞字符'x',然後檢查是否傳遞了「x」 - >中斷循環。

while (scanner.hasNext()) { 
     if (scanner.hasNext("avg") == true) { 

      c = scanner.next("avg"); 
      while (scanner.hasNextInt()){ //THIS IS WHERE YOU USE hasNextInt()      
       int j = scanner.scanNextInt(); 
       a.processNumber(j); 
      } 
      System.out.println("End While"); 
      result += a.getResult(); 
      a.reset(); 
     } 
+0

我試試這:)看我的FIXed代碼。但是,只有當我在'avg'之後輸入'sum'或者'sum'之後輸入'avg'時纔會中斷。 – JohnDow

+0

固定代碼和控制檯輸出 – JohnDow

+0

@ VladislavIl'ushin您是否嘗試過String.equals(「」)?我想我明白你想要做什麼。只要輸入一個空字符串到控制檯輸入,然後在你的while循環中檢查你的字符串EQUALS(「」)。如果是,那就打破循環。希望這個信息有幫助! – Mechkov