2012-12-05 76 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