Dominykas Zakrys
Dominykas Zakrys

Reputation: 11

NoSuchElementException reffers to first scanner when another is created

so there is probably someone in the group who has similar problem but i couldn't find close one as mine. I cant make 2 scanners work, one after another... adding 2nd scanner makes 1st go nuts and throw

"NoSuchElementException"

at the start of the scanner command. here is my code:

public class Stiklainiai {

static Scanner program = new Scanner(System.in);
static Scanner name_input = new Scanner(System.in);

public static void main(String[] argumentai){



    System.out.println("Welcome to Java IDE !");

    name();
    jar();


}


public static String name() {



    String name_select;
    System.out.println("name yourself");
    name_select = name_input.next();
    name_input.close();

    return name_select;

}

public static int jar(){


    int jar_select;                         // input variable (1-6) for "if" statement

    int jar_weight_assigned = 0;                   //unassigned capacity (applied by default if error occurs (outside 1-6 bounds))
    String jar_name_assigned = "";               //unassigned name (applied by default if error occurs (outside 1-6 bounds))

    int custom_jar_cap = 0;                     //custom "int" variable (custom jar)
    String custom_jar_name = "";                 //custom "String" variable (custom jar)

    int[] jar_weight_arr = new int[5];         //jar capacity array
    String[] jar_name_arr = new String[5];  //jar name array

    jar_weight_arr[0] = 9;
    jar_weight_arr[1] = 99;
    jar_weight_arr[2] = 999;
    jar_weight_arr[3] = 9999;
    jar_weight_arr[4] = 99999;

    jar_name_arr[0] = "bybiene22";
    jar_name_arr[1] = "bybiene44";
    jar_name_arr[2] = "bybiene66";
    jar_name_arr[3] = "bybiene88";
    jar_name_arr[4] = "bybiene000";

    jar_select = program.nextInt();
    ...
    ...
    ...

and so on goes the rest of the code.

when i run it i can input a name but afterwards i get "NoSuchElementException" that refers to:

jar_select = program.nextInt(); (where the scanner opens)

followed by the declared method error in main method:

jar();

rest of the code works fine with just one scanner...

my point is to make one method with separate scanner that assigns name to the "x" variable, and returns the value to main method. Then, the second runs the rest of the program in the other method, using the "x" variable with the value imputed

anyone knows the cause, i'm fairly fresh in java :)

Upvotes: 0

Views: 55

Answers (1)

Glains
Glains

Reputation: 2863

The problem is hidden behind Scanner.close. Whenever you close the Scanner, you also close the underlying System.in, so it wont be available the text time your access it using your second scanner.

Solution: Do not close the first Scanner.

Upvotes: 0

Related Questions