java - java中while循环接收到空字符串时如何输出空行?

标签 java string while-loop

我试图创建一个可以从一行读取 0 到 2 个数字的计算器。 如果它收到数字,则会将它们相加。如果仅输入一个整数,则会将其复制为输出。如果行为空,则计算器也应立即输出空行并继续要求输入。但是,它会这样做,但不会立即执行,并且仅在输入下一行数字时才跳过行。 这是我的代码

package calculator;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            //for the sake of stopping the code
            if (input.equals("/exit")) {
                System.out.println("Bye!");
                break;
            } else if (input.isEmpty()){
                System.out.println();
            }
            else{
                String[] array = input.split(" ");
                int[] numbers = new int[array.length];
                for (int i = 0; i < array.length; i++){
                    numbers[i] = Integer.parseInt(array[i]);
                }
                int sum = 0;
                for (int i = 0; i < numbers.length; i++){
                    sum += numbers[i];
                }
                System.out.println(sum);
            }

        }

    }
}

更新

通过将scanner.hasNext()更改为scanner.hasNextLine()解决了该问题。

最佳答案

事实证明,Scanner.hasNext 一直处于阻塞状态,直到非空输入为止。如果存在空行,则将其替换为 Scanner.hasNextLine 不会阻塞。

以下是如何使用 BufferedReader 来完成此操作。当你按下回车键时,即使有一个空行,它也会返回。

import java.io.*;
public class Main{
  public static void main(String[] args) throws Exception{
     BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
     boolean running = true;
     while( running ){
       String line = r.readLine();

       System.out.println("recv: " + line);
     }
  }
}

关于java - java中while循环接收到空字符串时如何输出空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60991546/

相关文章:

python - 变为 false 后如何返回到代码开头?

java - while 循环之外的语句被忽略?

java - 如何检索列表中具有某些属性的所有对象?

java - 如何减轻连接 com.mysql.jdbc.JDBC4Connection@11d08960 触发的连接泄漏,

java - Selenium 方法 - maximize() 和 fullscreen() 之间有什么区别

c - bsearch() - 在结构数组中查找字符串

java - 如何在showMessageDialog中打印双二维数组?

c - 使用 strcat 在字符串文字上添加空格?

php - 使用 while 循环回显 PHP 数组

Java 类级锁与对象级锁