您可以从扫描仪中读取整个输入行,然后将其分开,
,然后得到一个
String[],将每个数字解析为
int[]与索引一对一匹配的…(假设输入有效且不存在
NumberFormatExceptions),例如
String line = scanner.nextLine();String[] numberStrs = line.split(",");int[] numbers = new int[numberStrs.length];for(int i = 0;i < numberStrs.length;i++){ // Note that this is assuming valid input // If you want to check then add a try/catch // and another index for the numbers if to continue adding the others (see below) numbers[i] = Integer.parseInt(numberStrs[i]);}正如YoYo的答案所暗示的那样,以上内容可以在Java 8中更简洁地实现:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();处理无效输入
在这种情况下,您将需要考虑要执行的操作,是否想知道该元素输入错误,或者只是跳过它。
如果您不需要了解无效输入,而只想继续解析数组,则可以执行以下操作:
int index = 0;for(int i = 0;i < numberStrs.length;i++){ try { numbers[index] = Integer.parseInt(numberStrs[i]); index++; } catch (NumberFormatException nfe) { //Do nothing or you could print error if you want }}// Now there will be a number of 'invalid' elements // at the end which will need to be trimmednumbers = Arrays.copyOf(numbers, index);我们应该修剪结果数组的原因是,末尾的无效元素
int[]将由a表示
0,需要将这些元素删除以区分有效输入值
0。
结果是
输入:“ 2,5,6,bad,10”
输出:[2,3,6,10]
如果以后需要了解无效输入,可以执行以下操作:
Integer[] numbers = new Integer[numberStrs.length];for(int i = 0;i < numberStrs.length;i++) { try { numbers[i] = Integer.parseInt(numberStrs[i]); } catch (NumberFormatException nfe) { numbers[i] = null; }}在这种情况下,输入错误(不是有效的整数),该元素将为null。
结果是
输入:“ 2,5,6,bad,10”
输出:[2,3,6,null,10]
您可以通过不捕获异常来提高性能(有关更多信息,请参见此问题),并使用其他方法检查有效整数。



