Java 如何在数组中输入一行数字?

Java 如何在数组中输入一行数字?,java,arrays,input,Java,Arrays,Input,我想在一行中输入几个数字,就像这样 143329612 1 然后用空格分隔数字,并将它们全部放在一个数组中。 我该怎么做呢? 另外,我如何确保他们输入的每个数字都是整数,并且他们输入的数字少于10个?可能使用try/catch异常?这里有一些代码可以达到预期的效果: int[] nums; try { String line = ...; // read one line and place it in line StringTokenizer tok = new StringT

我想在一行中输入几个数字,就像这样

143329612 1

然后用空格分隔数字,并将它们全部放在一个数组中。 我该怎么做呢?
另外,我如何确保他们输入的每个数字都是整数,并且他们输入的数字少于10个?可能使用try/catch异常?

这里有一些代码可以达到预期的效果:

int[] nums;
try {
    String line = ...; // read one line and place it in line
    StringTokenizer tok = new StringTokenizer(line);
    if (tok.countTokens() >= 10)
        throw new IllegalArgumentException(); // can be any exception type you want, replace both here and in the catch below
    nums = new int[tok.countTokens()];
    int i = 0;
    while (tok.hasMoreTokens()) {
        nums[i] = Integer.parseInt(tok.nextToken());
        i++;
    }
} catch (NumberFormatException e) {
    // user entered a non-number
} catch (IllegalArgumentException e) {
    // user entered more that 10 numbers
}
结果是
nuns
数组包含用户输入的所有整数。当用户键入非整数或超过10个数字时,catch块被激活。

读入该行

String line = // how ever you are reading it in
按空间分割,查看文档中的

如果(number.length>10)/,请检查尺寸
。。。太大了

检查每个数组是否为整数,查看并放入新数组,所有这些都放在一起

 String line = //How you read your line
 String[] numbers = line.split("\\s");

 if(numbers.length <= 10)
 {
     int[] myNumbers = new int[numbers.length]
     int i = 0;
     for(String s:numbers) {
        try {
             int num = Integer.parseInt(s);
             myNumbers[i] = num;
             i++;
         } catch (NumberFormatException nfex) {
             // was not a number
         }
     }
  }
  else
      // To many numbers
stringline=//你是如何读这行的
字符串[]数字=行。拆分(\\s”);
如果(number.length
String line=“12 53 296 1”;
字符串[]行=s.split(“”);
int[]number=新int[splitted.length];
布尔正确=真;
if(splited.length)一个不必要的
 String line = //How you read your line
 String[] numbers = line.split("\\s");

 if(numbers.length <= 10)
 {
     int[] myNumbers = new int[numbers.length]
     int i = 0;
     for(String s:numbers) {
        try {
             int num = Integer.parseInt(s);
             myNumbers[i] = num;
             i++;
         } catch (NumberFormatException nfex) {
             // was not a number
         }
     }
  }
  else
      // To many numbers
String line = "12 53 296 1";
String[] line= s.split(" ");
int[] numbers = new int[splitted.length];
boolean correct=true;
if(splitted.length <10)
{
    correct=false;
}
for(int i=0;i<splitted.length;i++)
{
    try
    {
        numbers[i] = Integer.parseInt(splitted[i]);
    }
    catch(NumberFormatException exception)
    {
        correct=false;
        System.out.println(splitted[i] + " is not a valid number!");
    }
}