【发布时间】:2012-12-29 07:29:41
【问题描述】:
我的项目有问题,因为我无法正确开始,即从用户那里读取一行由空格分隔的整数并将值放入数组中。
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。
谁能帮助我?换一种方式会更好吗?
【问题讨论】:
-
阅读
next()方法的[文档](docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()。 -
每个人都给出了明显的替代解决方案,但在 OP 的代码中找到错误会更有趣(我没有)。
-
@dystroy:错误是,他使用的是
sc.next();而不是sc.nextLine(); -
@jlordo 很好看。这应该是(唯一的)答案。
-
@NickHolt:我很确定它引用了
java.util.Scanner
标签: java arrays string integer