Java - 如何将由空格分隔的整数读入数组 [英] Java - How to read integers separated by a space into an array
问题描述
我的项目遇到问题,因为我无法得到正确的结论,即读取由用户空格分隔的整数行并将值放入数组中。
I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.
System.out.println("Enter the elements separated by spaces: ");
String input = sc.next();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + count);
int[] arr = new int[count];
for(int x = 0;x < count;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
}
这就是我所拥有的,它似乎只是读取了第一个元素数组,因为当初始化count时,由于某种原因它被设置为1.
This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.
任何人都可以帮助我吗?以不同的方式做这件事会更好吗?
Can anyone help me? Would it be better to do this a different way?
推荐答案
只需要做一些微小的改动就可以使你的代码工作。 错误在此行中:
There is only a tiny change necessary to make your code work. The error is in this line:
String input = sc.next();
正如我在问题评论中指出的那样,它只读取下一个输入标记。请参阅文档。
As pointed out in my comment under the question, it only reads the next token of input. See the documentation.
如果用
String input = sc.nextLine();
它会做你想做的事,因为 nextLine()
消耗整行输入。
it will do what you want it to do, because nextLine()
consumes the whole line of input.
这篇关于Java - 如何将由空格分隔的整数读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!