Home > Software engineering >  Java do while Loop not continuing
Java do while Loop not continuing

Time:11-05

My do while loop repeats if it receives an invalid input. But then it won't accept a valid input. Where am I going wrong?

So I'm reading the first character in a line from a file and then matching that with user input. If user input matches, this works. If user input doesn't match, it gets stuck in the loop asking for the input again. Which it should do, but also should accept once valid input entered and then end.

public class test {

public static void selection() throws FileNotFoundException {
    boolean f = false;
    Scanner keyboard = new Scanner(System.in);

    System.out.println("Make booking:");

    Scanner file = new Scanner(new File("list.csv"));
    do {
        System.out.print("        Select the car number from the car list: ");
        char input = keyboard.next().charAt(0);
        String storeInput = "";

        while (file.hasNextLine()) {
            storeInput = file.nextLine();
            String finalInput = storeInput;
            if (storeInput.charAt(0) == input) {
                finalInput = finalInput   (" is the booking ");
                System.out.println(finalInput);
                f = true;
            }
        }
        if (!f) {
            System.out.println("Invalid car selection");
        }
    } while (!f);

}

public static void main(String[] args) throws FileNotFoundException {
    selection();
}

}

CodePudding user response:

Your do while loop is all the way correct but the problem is that your are not updating f if the input and the first letter doesn't match.

So instead of do while loop just ask the user for inputs just only one time if you want it to be or else create another boolean or use integers variable with values 0, 1 or 2.

CodePudding user response:

I see multiple problems. What if the file is empty?
Your problem would be that the file is completely read. So the secound iteration of the outer loop has no more lines to reed and no matching character can be found.

CodePudding user response:

Putting Scanner file = new Scanner(new File("list.csv")); into the do-while loop will be a good try

  • Related