Question

Currently running JUnit tests and I keep getting the above error. I've declared a public, static Scanner in my class and then access it from a different package which contains the test classes:

The following code (in ClassA) will keep on looping until user enters correct input.

public static Scanner sc;

public boolean methodInClass() {
    sc = new Scanner(System.in);
    for (; ; ) {
        for (int i = 0; i < 10; i++) {

            System.out.println("Please enter character. Enter A/B/C/D");
            char guess = sc.next().charAt(0);

            if (!correct) {
                System.out.println("Please enter a new guess");

                guess = sc.next().charAt(0);

            } 

///rest of code

In the test class:

This is an @Test method, and uses the following lines to simulate the Scanner:

String input = "L\nL\nD\nU\nA\n";
System.setIn(new java.io.ByteArrayInputStream(input.getBytes()));
ClassA.sc = new Scanner(System.in); //should stop at A which is correct input
Was it helpful?

Solution

You never change correct value to TRUE, so it checks all 5 leters, trys to take 6th, and crashes. After

char guess = sc.next().charAt(0);

add

correct = guess=='A';

also, your top for cycle never ends. So you probably want add break somewhere.

Edit: and while correct == false you are reading 1st, 3rd, 5th symbol. Probably you didn't intended to do that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top