【发布时间】:2020-07-14 10:08:12
【问题描述】:
我试图创建一个从一行中读取 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() 解决了这个问题。
【问题讨论】:
-
扫描仪“nextLine”在收到非空行之前不会返回。然后它接收所有这些。缓冲阅读器怎么样?
-
while (scanner.hasNext()) {应该是while (scanner.hasNextLine()) {
标签: java string while-loop