我想在一行中输入几个数字,如此,
14 53 296 12 1
并用空格分隔数字,并将它们全部放在一个数组中。 我该怎么做呢? 另外,我怎样才能确保他们输入的每个数字都是一个整数,并且输入的数字少于10个?也许使用try / catch异常?
答案 0 :(得分:0)
这是一些实现预期效果的代码:
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块。
答案 1 :(得分:0)
阅读
中的一行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
答案 2 :(得分:0)
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!");
}
}
现在数组编号包含已解析的数字,布尔值正确显示每个部分是否为数字且不少于10个数字。