gpt4 book ai didi

java - 为什么在使用 Scanner 从单行读取整数列表时会出现无限循环?

转载 作者:行者123 更新时间:2023-11-29 08:09:43 26 4
gpt4 key购买 nike

我需要用户在一行中输入一个整数列表,所以我这样写:

public static Integer[] readIntegers()
{
Scanner input = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();
do list.add(input.nextInt());
while(input.hasNextInt());
return list.toArray(new Integer[list.size()]);
}

但它一直在循环!如果扫描仪上没有数字,hasNextInt() 不应该返回 false 吗?我怎样才能修复以前的方法?或者我应该改用 nextLine() 并溢出字符串?

最佳答案

System.in 不会因为您按下回车键而“结束”。如果你想这样做,你可能会在 while 表达式中检查 '\n'

一般来说,我更愿意用另一种方式来做:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine(); // line == null indicates end of input.

或使用 java.io.Console

此外,如果您使用 do/while 而不是 while,如果输入为空,您可能会遇到问题。

关于java - 为什么在使用 Scanner 从单行读取整数列表时会出现无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8853011/

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