0

我使用这段代码:

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;
}

当我按下回车或发送空行时,我需要在循环(hasNexInt())时结束。

我尝试使用 String == null 等的一些方法,但 Java 只是 IGNORE 空行

输出

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
4

4 回答 4

1

只需使用类似的东西:

String line = null;
while(!(line = keyboard.nextLine()).isEmpty()) {
// Your actions
}
于 2012-12-05T14:28:42.120 回答
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();
        }
于 2012-12-05T14:30:55.333 回答
1

如果在您的应用程序中使用 Scanner 不是绝对必须的,我可以提供:

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

此代码肯定会在控制台的空行上停止。现在您可以使用 Scanner 进行行处理或正则表达式。

于 2012-12-05T15:36:44.270 回答
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);
            }
于 2012-12-05T14:29:23.107 回答