Java – 如何将由空格分隔的整数读入数组

我的项目有问题,因为我无法得到正确的开头,即读取由用户空格分隔的整数行并将值放入数组中。

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

正如我在该问题的评论中指出的那样,它只读取输入的下一个标记。 请参阅文档 。

如果你用它替换它

 String input = sc.nextLine(); 

它会做你想做的事,因为nextLine()会消耗整行输入。

 String integers = "54 65 74"; List list = new ArrayList(); for (String s : integers.split("\\s")) { list.add(Integer.parseInt(s)); } list.toArray(); 

有其他方法可以实现同样的目标。 但是当我尝试你的代码时,它似乎正常工作。

 StringTokenizer strToken = new StringTokenizer("abc"); int count = strToken.countTokens(); System.out.println(count); 

它打印计数为3.默认的demiliter是“”

我不知道你是如何获得输入字段的。 可能是它没有以字符串格式返回完整的输入。

我认为您正在使用java.util.Scanner来读取您的输入

来自扫描仪的java doc。

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。 然后可以使用各种下一种方法将得到的标记转换成不同类型的值。

因此,输入只返回一个整数,其余部分无人值守

读这个。 扫描 仪#next() ,您应该使用Scanner#nextLine()代替

这将是一种更简单的方法 –

 System.out.println("Enter the elements seperated by spaces: "); String input = sc.nextLine(); String[] split = input.split("\\s+"); int[] desiredOP = new int[split.length]; int i=0; for (String string : split) { desiredOP[i++] = Integer.parseInt(string); } 
 import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); . . . StringTokenizer st = new StringTokenizer(br.readLine()); int K = Integer.parseInt(st.nextToken()); int N= Integer.parseInt(st.nextToken());