0

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.

2 Answers 2

2

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

do {
    input = System.in.read();
    ...
} while (input != '.');
Sign up to request clarification or add additional context in comments.

Comments

1

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.