线程 "main" java.util.NoSuchElementException 中的异常,同时获取未知数量的输入然后获取另一个输入
Exception in thread "main" java.util.NoSuchElementException while getting unknown number of inputs and then getting another input
我最初使用 hasNext()
在数组中获取未知数量的输入,然后获取另一组输入但获取 NoSuchElementException
。
代码片段:
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = new int[100];
int input = 0;
while (sc.hasNext()) {
array[input++] = sc.nextInt();
}
int k = sc.nextInt();
int[] newArray = new int[100];
int j = 0;
for (int h = 0; h < k; h++)
newArray[j++] = sc.nextInt();
}
}
你读取了所有的值,然后调用了 int k=sc.nextInt();再次。这就是异常的原因。尝试添加一些逻辑以更确定的方式获取所有输入。
来自来源
/**
* Scans the next token of the input as an <tt>int</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextInt()</tt> behaves in exactly the same way as the
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt() {
return nextInt(defaultRadix);
}
我最初使用 hasNext()
在数组中获取未知数量的输入,然后获取另一组输入但获取 NoSuchElementException
。
代码片段:
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] array = new int[100];
int input = 0;
while (sc.hasNext()) {
array[input++] = sc.nextInt();
}
int k = sc.nextInt();
int[] newArray = new int[100];
int j = 0;
for (int h = 0; h < k; h++)
newArray[j++] = sc.nextInt();
}
}
你读取了所有的值,然后调用了 int k=sc.nextInt();再次。这就是异常的原因。尝试添加一些逻辑以更确定的方式获取所有输入。 来自来源
/**
* Scans the next token of the input as an <tt>int</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextInt()</tt> behaves in exactly the same way as the
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt() {
return nextInt(defaultRadix);
}