我想像这样在一行中输入几个数字,
14 53 296 12 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
按空间分割,查看文档String.split()
String[] numbers = line.split("\\s");
检查尺寸if(numbers.length > 10) //... to large
检查每个都是整数,看看Integer.parseInt()
,然后放入你的新数组,所有这些都在一起......
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!");
}
}
现在数组 numbers 包含解析的数字,并且布尔正确显示每个部分是否都是数字并且不少于 10 个数字。