0

I'm getting an unknown number of inputs in an array initially using hasNext() and the getting another set of inputs but getting NoSuchElementException.

Code snippet:

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();
    }
}
catch23
  • 13,661
  • 38
  • 120
  • 194
  • Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – sleepToken Feb 04 '20 at 15:33
  • Dump/debug the contents of sc after the while loop. My expectation is that when sc.hasNext() returns false that sc.nextInt() would not reference anything. – Martin Feb 04 '20 at 17:00

1 Answers1

0

You read all the values and then called int k=sc.nextInt(); again. Thats the reason of Exception. Try to add some logic to get all input in more deterministic manner. From the source

/**
 * 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);
}
Abhi
  • 120
  • 10