Parry Chen
Parry Chen

Reputation: 49

Stopping a loop when receiving a specific character for input

I have written code that changes uppercase letters to lowercase letters and vice versa. I'm trying to use break so that I can exit the loop whenever the input is '.', and it doesn't seem to be working. Any advice would be appreciated! I also want to create a count of all the time the loops reiterated before it ended. How would I go about that?

public static void main(String[] args) throws java.io.IOException {

    char choice, ignore = 0;
    for (; ; ) {
        do {
            System.out.print("Please enter a upper or " + "lower case letter(. to quit)");
            choice = (char) System.in.read();
            if ((char) choice > 64) {
                ignore = (char) (choice + 32);
            }
            if ((char) choice > 96) {
                ignore = (char) (choice - 32);
            }
            System.out.print(ignore);
            System.out.println("\n");
            if (choice == '.') {
                break;
            }
            do {
                ignore = (char) System.in.read();
            } while (ignore != '\n');
        } while ((char) choice > 64 | (char) choice < 123 | choice != '.');
    }
}

Upvotes: 1

Views: 1996

Answers (4)

Parry Chen
Parry Chen

Reputation: 49

stackoverflow.com/q/886955/4793951 Break labels Thanks! @Zircon

Upvotes: 0

niraj
niraj

Reputation: 18208

Even though your while loop breaks, the for loop keeps on running forever. One fix may be to add the terminating condition within for loop.

 for (; choice != '.'; ) 

Please make sure to initialize the choice variable or else it would throw error during compile.

Upvotes: 0

duncan
duncan

Reputation: 1161

The problem is you have a nested loop. Your for (; ; ) will not be exited because the break will only escape from:

do {
    //other code
} while ((char) choice > 64 | (char) choice < 123 | choice != '.');

You have a few options but probably the easiest would be to change the for loop to something like this:

while(choice != '.'){
     //do other code
}

This way when the break is reached your code will exit the do while and exit the while on the next loop.

Keep in mind with this technique you will have to initialize choice with a value.

Upvotes: 1

DeeV
DeeV

Reputation: 36035

You have a do-while loop inside a permanent for-loop. The break statement is going to break you out of the do-while loop, but you're still in the for-loop. It will just re-enter the do-while loop again and keep going.

Upvotes: 0

Related Questions