English 中文(简体)
为什么在使用斯堪的纳语阅读单一线的惯犯清单时,会有什么定点?
原标题:Why is there an infinite loop when reading a list of integers from a single line using Scanner?

我需要用户在单一线路上填写一份分类账清单,因此我写道:

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()]);
}

但它坚持永远 lo! 页: 1 扫描仪上没有数字吗? 我如何确定先前的方法? 或者,我是否应当使用nextLine()取代并混淆了Sting?

最佳回答

System.in does not "end" because you press enter. If you want to do it this way, you could probably check for in the while expression.

总的来说,我倾向于以另一种方式这样做:

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

或使用<代码>java.io.Console。

而且,如果你使用的话,如果投入是空的,那么你就会遇到问题。

问题回答

我相信,你只是把EOF带至你的圈子,因此,你的方案正在等待下一次投入。

EOF, 在窗户上使用ctrl+zctrl+d

如果你刚刚读到一条单行,将其内容放在一个<条码>上,那将更好。 这样,使用者就不必在现场访问,而只能进入报界。

另外,你希望有<条码>,而不用<条码>,因为没有数字。 由于<代码>d.while首先检查了一次振荡后的状况,你的代码试图读到至少一种愤怒,即使有点。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签