我的项目有问题,因为我无法得到正确的开头,即读取由用户空格分隔的整数行并将值放入数组中.
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.
谁能帮我?以不同的方式做这件事会更好吗?
解决方法
只需进行一些微小的更改即可使代码正常工作.错误在这一行:
String input = sc.next();
正如我在该问题的评论中指出的那样,它只读取输入的下一个标记.见documentation.
如果你用它替换它
String input = sc.nextLine();
它会做你想做的事,因为nextLine()
会消耗整行输入.