gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:39:10 26 4
gpt4 key购买 nike

我试图创建一个可以从一行读取 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com