使用 Scanner 在一行中读取多个数字
Reading multiple numbers on a single line with Scanner
我需要使用扫描仪从一行中读取多个数字(不知道我要读取多少个数字,但我知道它们最多六个数字)。我尝试了在网上找到的一些东西,但找不到解决方案。当用户写入 -1 时,读取停止。这是我到目前为止写的:
Scanner read = new Scanner(System.in);
int i;
float buffer[] = new float[6];
while (read.nextInt() != -1) {
if (read.hasNextInt()) {
buffer[i] = read.nextInt();
i++;
} else {
break;
}
}
当我尝试 运行 时,我得到 NoSuchElementException
,但我不明白为什么。这段代码有什么问题?我该如何纠正这个问题?提前致谢。
因为你没有检查 Scanner
是否有另一个 int
(而 Scanner
没有 return -1
当它没有有另一个元素)。这个
while (read.nextInt() != -1) {
需要类似于
while (read.hasNextInt()) {
int val = read.nextInt();
if (val == -1) {
break;
}
buffer[i] = val;
i++;
}
或者你可以读取一行,然后将其拆分为整数
line=scanner.nextLine();
// split there
String elements[]=line.split("\W+");
// convert to int
for (int i=0;i<elements.length;i++)
ints[counter++]=Integer.parseInt(elements[i]);
// check
for (int i=0;i<counter;i++)
System.out.println("INT ["+i+"]:"+ints[i]);
我需要使用扫描仪从一行中读取多个数字(不知道我要读取多少个数字,但我知道它们最多六个数字)。我尝试了在网上找到的一些东西,但找不到解决方案。当用户写入 -1 时,读取停止。这是我到目前为止写的:
Scanner read = new Scanner(System.in);
int i;
float buffer[] = new float[6];
while (read.nextInt() != -1) {
if (read.hasNextInt()) {
buffer[i] = read.nextInt();
i++;
} else {
break;
}
}
当我尝试 运行 时,我得到 NoSuchElementException
,但我不明白为什么。这段代码有什么问题?我该如何纠正这个问题?提前致谢。
因为你没有检查 Scanner
是否有另一个 int
(而 Scanner
没有 return -1
当它没有有另一个元素)。这个
while (read.nextInt() != -1) {
需要类似于
while (read.hasNextInt()) {
int val = read.nextInt();
if (val == -1) {
break;
}
buffer[i] = val;
i++;
}
或者你可以读取一行,然后将其拆分为整数
line=scanner.nextLine();
// split there
String elements[]=line.split("\W+");
// convert to int
for (int i=0;i<elements.length;i++)
ints[counter++]=Integer.parseInt(elements[i]);
// check
for (int i=0;i<counter;i++)
System.out.println("INT ["+i+"]:"+ints[i]);