0

I'm an amateur with Java and am trying to put the contents of a scanner into an array. This is what I have currently: `

public static void main(String args[])
    { 
        Scanner sc = new Scanner(System.in);
        int l = scannerLength(sc);
        sc.close(); sc = null; sc = new Scanner(System.in);
        int[] input = new int[l];
        for (int i = 0; i < l; i++) {
            input[i] = sc.nextInt();
            System.out.println(input[i]);
        }
    }


private static int scannerLength(Scanner sc) {
    int output = 0;
    while(sc.hasNextInt()) {
        output++;
        sc.nextInt();
    }
    return output;
}
`

I am trying to effectively 'reset' the Scanner after my helper function determines its length by voiding it and declaring it anew, so I can use nextInt to put the elements into an array. But I get a NoSuchElementException at line 8.

Can anyone tell me why this is? I would think, after resetting the Scanner, that sc.nextInt() at line 8 wouldn't pose a problem.

BCD
  • 131
  • 1
  • 1
  • 3
  • see this: http://stackoverflow.com/questions/8203981/closing-bufferedreader-and-system-in pretty sure you cant close system.in like that – nhouser9 Feb 11 '17 at 02:52
  • Please define what do you consider as "scanner length" – Nir Alfasi Feb 11 '17 at 02:52
  • 1
    Possible duplicate of [java.util.NoSuchElementException - Scanner reading user input](http://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Tom Feb 11 '17 at 02:52
  • System.in is guaranteed to be a sequence of integers, so "scanner length" is the number of integers in the input stream. I was able to find a work around using the link that Tom posted. Thank you! – BCD Feb 12 '17 at 21:46

0 Answers0