Java Autograder in Teams doesn't work with multiple scanners

I’ve been starting to make my own autograders in my Teams class for teaching Java in Computer Science.

There’s a bug with Scanner where if you ask it to read “nextInt()” or “nextBoolean()” and then ask it to read the “nextLine()”, it will skip over the input. Anyone familiar with Java should know about that one.

The problem is that I’ve been teaching my students that a good way to get around that is to simply use two Scanners; one for nextLine() and one for all other methods calls.
And what I’m discovering now though is that when I use the “Input Output Tests” in those tasks to read a certain input, having the two Scanners breaks the program.

Code that works:

import java.util.*;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    
    //prompt
    System.out.println("Welcome to the program! How many students do you need to enter?"); 

    int num = sc.nextInt();

    //generates array of appropriate size
    String[] list = new String[num];

    //clear Scanner
    String name = sc.nextLine();

    //fills array with user input
    for (int i = 0; i < num; i++) {
      System.out.println("Enter name of student #" + (i+1) + ": ");
      list[i] = sc.nextLine();
    }

    System.out.println("\nHere is the complete list of students: ");

    //prints the list
    for (int i = 0; i < num; i++) {
      System.out.println(list[i]);
    }
  }
}

And this code results in the error:

Exception in thread "main" java.util.NoSuchElementException: No line found
	at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
	at Main.main(Main.java:23)
//this task is practice; not for marks
//follow the instructions for the task on D2L
//submit both to the D2L assignment folder and here on Replit to move onto the next task

import java.util.*;

class Main {
  public static void main(String[] args) {
    Scanner line = new Scanner(System.in);
    Scanner sc = new Scanner(System.in);
    
    //prompt
    System.out.println("Welcome to the program! How many students do you need to enter?"); 

    int num = sc.nextInt();

    //generates array of appropriate size
    String[] list = new String[num];

    //fills array with user input
    for (int i = 0; i < num; i++) {
      System.out.println("Enter name of student #" + (i+1) + ": ");
      list[i] = line.nextLine();
    }

    System.out.println("\nHere is the complete list of students: ");

    //prints the list
    for (int i = 0; i < num; i++) {
      System.out.println(list[i]);
    }
  }
}

Can anyone please help me understand why this is? And if there’s some way around it so that it will work for multiple Scanners?

Thanks in advance

1 Like