user11287089
user11287089

Reputation:

While Loop Not Closing When Condition Is Met

    public void enroll() {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter course to enroll (Q to quit)");
        while(!in.nextLine().equals("Q")) {
            courses.add(in.nextLine());
        }
    }

The program should accept user input and add it to the ArrayList courses until the user enters "Q" but instead what's happening is that it seems like it's only registering and adding every other input. It's also adding the Q which is an issue.

Upvotes: 0

Views: 69

Answers (2)

MediaNik Ok
MediaNik Ok

Reputation: 121

Your code doesn't do what you want it to do. How it should be: users inputs are processed one per iteration and if it's 'Q', then quit while. How it actually is: users inputs are processed two per iteration(because you cal in.nextLine() both in conditional part and in body of while), and if first is not 'Q' then add second to list.

Here is my code to this:

    Scanner in = new Scanner(System.in);
    System.out.println("Enter course to enroll (Q to quit)");
    String line;
    while(!(line = in.nextLine()).equals("Q")) {
        courses.add(line);
    }

Upvotes: 1

sorifiend
sorifiend

Reputation: 6307

Your issue is that you are getting the next line twice, firstly inside the loop condition while(!in.nextLine().equals("Q")) { then again inside the loop courses.add(in.nextLine());.

One solution could be to use a string variable to store the line, and an if check to see if the condition is met:

public void enroll() {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter course to enroll (Q to quit)");
    String line = "";
    while(true) {
        //We should only get the next line once per loop:
        line = in.nextLine();
        //Now we can use the line
        if (line.equals("Q")){
            break;
        }
        courses.add(line);
    }
}

Upvotes: 0

Related Questions