java - 线程“main”中的异常java.util.NoSuchElementException,同时获取未知数量的输入,然后获取另一个输入

我最初使用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);
}