Stopping a loop when receiving a specific character for input - java

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 != '.');
}
}

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.

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.

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.

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

Related

Using while loop for nested if statements

Although I know I'm missing something, can't seem to get my head around a simple loop.
while (true){
if (n < 0)
System.out.print("less than 0")
else if (n > 35)
System.out.print("greater than 35")
else
calc(n)
}
I'm trying to use a while loop to loop the code and asks for input until the user inputs a value greater than 0 and less than 35, I have tried using continue but too no avail, thanks in advanceenter image description here
I have added sc of full code, the while loop will go after requesting input at the bottom of the code
// if using jdk 1.7 or above else close scanner in finally block.
try (Scanner s = new Scanner(System.in)) {
int n;
while (true) {
n = s.nextInt();
if (n < 0) {
// ask for value greater then 0
System.out.print("Please enter a value greater then 0 ");
// extra print statement so input will be printed on next line after message
System.out.println();
} else if (n > 35) {
// ask for value less then 35
System.out.print("Please enter a value less then 35");
System.out.println();
} else {
// process input and break if correct input has received
calc(n);
break;
}
}
}
Well you aren't "asking for input". Also the while loop will NEVER exit. You probably at the minimum want a break in there somewhere.
I think you are missing the input for the user:
Scanner in = new Scanner(System.in);
int n = 0;
while (n != 27){ /*Can be any number here instead of 27, even -1*/
n = in.nextInt();
if (n < 0)
System.out.print("less than 0")
else if (n > 35)
System.out.print("greater than 35")
else
calc(n)
}
Also i would suggest you to not use while(true) becuase you will have endless loop, you can put instead a condition: while(n != 27)
So each time you enter 27 it will end the loop.
I am also not sure of that calc method but maybe you could use something like this?
Boolean checked = true;
While(checked) {
if (n < 0) {
System.out.print("less than 0");
}
else if (n > 35) {
System.out.print("greater than 35")'
}
else {
calc(n)
checked = false;
}
}
Hope it helps. Cheers
How about:
Scanner in = new Scanner(System.in);
int n = 0;
while (true){
n = in.nextInt();
if (n < 0)
System.out.print("less than 0");
else if (n > 35)
System.out.print("greater than 35");
else{
calc(n);
break;
}
}
You are missing two things in your code.
1) Inside while loop, there is no mechanism to update the value of variable n. i.e, if outside loop, the value of n is set to say 2, the loop will keep on printing Greater than 35. So a mechanism is needed to update it's value
2) Breaking mechanism for while loop. Because the condition is while(true) and there is no break inside the loop, the loop will continue endlessly. So, a loop breaking mechanism is needed
Below is a sample code where input is taken from console using Scanner and break is used for loop breaking condition
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = 0;
while (true) {
n = scan.nextInt();
if (n < 0)
System.out.print("less than 0");
else if (n > 35)
System.out.print("greater than 35");
else {
calc(n);
break;
}
}
scan.close();
}
you can use do while. like this:
do {
calc(n);
} while(n < 0 || n > 35)
expect calc(n) function read user input value and put it in n variable.

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.
This is actually the perfect time to use a do-while loop.
do {
input = System.in.read();
...
} while (input != '.');
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");

Initialising Issue

private void northroom()
{
char choice2;
boolean boolean_1 = false;
String answer2;
System.out.println("You press a panel next to the door");
System.out.println("The panel lights up with a pinging sound");
System.out.println("The door slowly scrapes open");
System.out.println("You are now in North Room");
System.out.println("There is a object in the coner of the room shoraded by darkness");
do
{
System.out.println("Would you like to pick up object Yes(Y) or No(N)");
while(boolean_1 == false)
{
answer2 = keyboard.next();
choice2 = answer2.charAt(0);
if(choice2 == 'Y')
{
System.out.println("You go pick up the object");
}
if(choice2 == 'N')
{
System.out.println("Stare at object because you are useless");
System.out.println("Try again");
}
}
}
while (**choice2** != 'Y' && **choice2** != 'N');
while (choice2 != 'Y' && choice2 != 'N');
Here both the choice2 are initialised how do I correct this so that it loops properly
The compilers code-path analyzer doesn't go far enough to recognize that the while(boolean_1 == false) loop will always execute at least once.
As far as the compiler is concerned, the loop body might be skipped, in which case the choice2 variable is unassigned, i.e. not definitely assigned.
You can fix that by initializing it to a dummy value, e.g.
char choice2 = ' ';
Of course, if the compiler did extended analysis, it would have found that the while(boolean_1 == false) loop runs forever, since boolean_1 is never updated, and would have generated compile error saying that while (choice2 != 'Y' && choice2 != 'N'); is unreachable.
I'm not sure what is the designed behavior for your nested loops. However, ur inner loop is a infinite loop. It can never end so outer loop can never check condition showed in last line of code

Java while loop not working with input checking of characters

The code below is from a game in which I need to generate 2 random numbers in java, and the user is presented with one of them. They then have to guess if the second number is higher or lower than the first. I created a while loop to check for errors in their input and the loop is executed even if the condition is not true. Entering H means their guess is the next number is higher, and L means they believe its lower
// Input
System.out.println ("Do you think the second number is higher or lower (enter 'H' or 'L' respectively): ");
char userGuess = Character.toUpperCase(input.next().charAt(0));
// Input error check (and immediate output of second number)
while (userGuess != 'H' || userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}
System.out.println ("The second number was " + secondRandomNumber);
Use && not ||. Of course it's not going to be H or not going to be L
while (userGuess != 'H' && userGuess != 'L') {
System.out.println ("Sorry, I didn't understand that. Please try again: ");
userGuess = Character.toUpperCase(input.next().charAt(0));
}

Having difficulty ignoring case sensitivity for do while loop

Trying to let the user exit the program using the letter 'N' or 'n' but it will only let them exit when using 'N'
Below is my code, any help is appreciated!!
System.out.print(" Do you want to repeat the ");
System.out.println("program ['Y' or 'N']");
Choice = sc.next().charAt(0);
} while (Choice != 'N' || Choice != 'n');
}
}
You have to use while (Choice != 'N' && Choice != 'n'); .
It must be AND condition. Not an OR condition.
You are using the wrong operator:
while (Choice != 'N' && Choice != 'n');
Right now, your code states that the loop will continue when the character is either not 'N' or not 'n'. Since the character can't be 'N' and 'n' at the same time, the loop will always continue. Switching the operator to a && requires that the character is neither N nor n to continue.

Categories

Resources