Gabriel St-Pierre
Gabriel St-Pierre

Reputation: 5

While loop repeating unexpectedly [Java]

I am currently following a book on java programming and I tried to do one of the self study questions that asks to make a program that counts how many times you press the space-bar and you have to hit '.' to stop the while loop. However, the loop seems to want to loop over 3 times rather than asking to enter a key again after one. Here is the code

public class KeySelfTest {
public static void main(String args[]) throws java.io.IOException{
    char input;
    int space = 0;

    input = 'q';

    while (input != '.'){
        System.out.println("Enter a key");
        input = (char) System.in.read();
        if (input == ' '){
            space++;
        }
        else{
            System.out.println("Enter a period to stop");
        }

    }
    System.out.println("You used the spacebar key " + space + " times");    
}
}

I was also wondering what I could use to initialize the input variable before the actual loop instead of just defaulting it to a random letter like q. Thanks for the help.

Upvotes: 0

Views: 55

Answers (2)

Strikeskids
Strikeskids

Reputation: 4052

This is actually the perfect time to use a do-while loop.

do {
    input = System.in.read();
    ...
} while (input != '.');

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201517

You can assign and test in one statement, like

char input;
int space = 0;

while ((input = (char) System.in.read()) != '.') {
    System.out.println("Enter a key");
    if (input == ' ') {
        space++;
    } else {
        System.out.println("Enter a period to stop");
    }
}
System.out.println("You used the spacebar key " + space + " times");

Upvotes: 1

Related Questions