How to terminate while loop once response is correct? - java

I'm working on this program that says "get some ice cream"/"put on a jacket" if you type "hot/cold". However, even after you type in hot/cold, the program keeps going in the while loop. How can I make this program keep asking the user for their condition until they correctly respond with one of the two answers, and prevent it from continuously asking for a response even after the user types a correct answer?
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
boolean run = true;
while(run) {
System.out.println("What is your condition: ");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
if(x.equals("hot"))
System.out.println("Get some ice cream");
else if(x.equals("cold"))
System.out.println("Put on a jacket");
else
System.out.print("Try again, what is your condition: ");
}
}
}

your loop iterates as long as run is true. what you need to do is therefore to set run to be false once the input is correct. like this
if(x.equals("hot")){
System.out.println("Get some ice cream");
run = false; // setting run to false to break the loop
}
else if(x.equals("cold")) {
System.out.println("Put on a jacket");
run = false; // setting run to false to break the loop
}

break statement can be used as well.

You may also use do while loop.
In this case, you would have the ability to check your condition against "x" when the loop ends, and hence would not need additional flag.
However, do while loop will run at least once, which I assume you need as per your requirement.

Related

How to ask te user and depending on his response run all the code again?

I'm a newbie in Java. I started these days and I'm practicing the catch and try exception. I have this code below which solve an operation between to numbers and I'd like to know what can I do, if for example I want that the user, once he makes an operation and get his result, that this has the possibility to make another operation. something like comes up a question asking if he wants to realize another problem and the code run again from the beginning.
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
int x=1;
while(x==1){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
x=2;
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
You can do, for example, adding an if statement with a
System.out.println("Do you want to recalculate ? (1/0 Yes/No)");
Operation.nextInt();
then if the input is 1, keep x = 1, else do x = 2.
Try this code amendment;
package justpractice;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner Operation = new Scanner(System.in);
//better practice
while(true){
try{
System.out.println("Insert numerator");
int n1 = Operation.nextInt();
System.out.println("Insert denominator");
int n2=Operation.nextInt();
double division = n1/n2;
System.out.println(division);
System.out.println("Continue? (y/n)");
String response = Operation.nextLine();
if (response.equals("n")){
break;
}
}
catch(Exception e){
System.out.println("Insert a valid value");
}
}
}
}
To allow your user to calculate division again, you could use a do-while loop. With this loop you can execute the code inside once, ask the user if they would like to calculate again, and repeat the code if they do.
An outline of your code with the loop would something like this:
...
boolean again = true;
do { //Main loop
try {
... //Your division code
... //Put code to ask the user if they want to calculate again here
} catch(Exception e) {
...
}
} while(again == true); //Repeat if the user wants to continue
To get input on if the user wants to calculate again, I recommend using another do-while loop with your Scanner. This loop will allow you to repeat the code when the answer is invalid. In this case, when it's not "y" or "n".
String input;
do {
System.out.println("Would you like to continue? (y/n)");
input = operation.next();
} while(!input.equalsIgnoreCase("y") && !input.equalsIgnoreCase("n"));
After you have got the user's input, you still need to terminate the loop if they said "n". To do this you could use an if statement.
if(input.equalsIgnoreCase("n")) {
again = false; //Terminate the main loop
operation.close(); //Prevent any resource leaks with your Scanner
}
There is no need to check if the user input "y" as again is set to true by default.
Side Note: Variables should always be camelCase. Look at the Java Naming Conventions to learn more about naming things in Java.
EDIT:
The reason the console is repeatedly logging that you entered a non-number even though you entered it once, I'm not exactly sure. I think it's because the call to nextInt() never finishes because of the InputMismatchException being thrown, causing the next call to nextInt() (After the do-while repeats) to think that the letter/symbol you just entered is the one you want to process, repeating the exception over and over again.
To solve this, add this line into your catch block:
if(operation.hasNext()) operation.next();
This will call next() and complete the process of marking the letter/symbol you just entered as already processed, then repeat the do-while loop as normal.

Java: What is the equivalent of != when comparing strings?

I would like the while loop to execute whenever the user enters a value other than "stop" or "continue" when ignoring case. How can I do this? Whenever I run the program it prints "Invalid entry" even if I type in continue or stop. What am I doing wrong?
package butt;
import java.util.*; // used for console input
public class butt_face{
static Scanner console = new Scanner(System.in); // needed for user input
public static void main(String[] args) {
String strContinue; // input from console and used for boolean
System.out.println("Would you like to stop or continue? ");
strContinue = console.next();
while(!(strContinue.equalsIgnoreCase("stop")) || !(strContinue.equalsIgnoreCase("continue")))
{
System.out.println("Invalid entry");
System.out.println("Would you like to stop or continue? ");
strContinue = console.next();
} // end while
if(strContinue.equalsIgnoreCase("stop")
{
System.out.println("Good bye!");
} // end if
else
System.out.println("Poop Ship Destroyer");
} // end of main
} // end of class
You have the wrong operator:
!(strContinue.equalsIgnoreCase("stop"))
is true unless strContinue is "stop".
!(strContinue.equalsIgnoreCase("continue"))
is true unless strContinue is "continue".
strContinue cannot be both "stop" and "continue", therefore at least one of the conditions will always be true, and false || true is true.
Solution: change the or (||) to an and (&&).
You need to replace with a && in the condition instead of ||
Check the repl https://repl.it/B6GJ/0
The issue is in your logic.
while(!(strContinue.equalsIgnoreCase("stop")) || ! (strContinue.equalsIgnoreCase("continue")))
This part checks if strContinue is equal to stop if it is equal to stop it will then check to see strContinue is equal to continue.
Do something like a input function that calls the input scanner until you entered one of these two strings.

While Loop executing one last time when condition is set to false

Task: To check that if a user input string has the same first and last character. If yes or no, output to the screen, if the user enters "done", the loop is exited.
Issue: While loop executes when condition is false
What I've tried: Using different types of loops, doing a loop within the loop to revalidate the code and all together giving up!
import java.util.*;
public class lab_15 {
public static void main(String args[]) {
String userInput = "";
String done = "done";
while (!userInput.equalsIgnoreCase(done))
{
int length;
Scanner sc = new Scanner(System.in);
userInput = sc.next();
length = (int)userInput.length();
if (userInput.charAt(0) == userInput.charAt(userInput.length()-1)) {
System.out.println("The first character equals the second character.");
}
else {
System.out.println("The first and second characters are different.");
}
}
// EXIT LOOP
System.out.println("Thank you for using this software!");
}
}
Inputs
+ bradley
+ hannah
+ done
I am still new to the site and have referred to the t's & c's regarding posts. Please do not negative if you find the question to not be challenging. I am new to programming and hope to progress.
Thank you!!!
This is because you change your userInput immediately once entering the loop. The condition is only checked when you reach the top of the loop, so if you invalidate the condition halfway through, it will continue executing until you reach the top.
The solution is to refactor so that the very last thing that happens is changing your userInput so that the condition is check immediately after the value is changed. (I would also pull the scanner instantiation out of the loop.)
Alternatively you could check your condition inside of the while loop and call break if the userInput has changed to match the terminating condition. The break keyword will force the logic to exit the loop immediately, without evaluating the condition again.

Beginner looping issue- while ... do

What the program does: Reads two values from input, asks user whether to add, subtract, or find the product. If user enters one of the three options, it calculates, otherwise the program will loop back to the beginning. The program should STOP after calculation if the user enters one of the three options.
I'm not sure why it keeps on looping. How do I make the script loop only when the user types in a string other than "sum", "difference", or "product"? Also, how can I make the code simpler? Is there any way to loop the program without using do ... while?
import java.util.Scanner;
import java.util.Random;
public class simp_calculator
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
double a, b;
String response;
boolean noresponse;
do
{
System.out.println ("Please enter first number.");
a = scan.nextDouble();
System.out.println ("Please enter second number.");
b = scan.nextDouble();
System.out.println ("Would you like to find the sum, difference, product?");
response = scan.next();
if (response.equalsIgnoreCase ("sum"))
{
System.out.println (a + b);
}
if (response.equalsIgnoreCase ("difference"))
{
System.out.println (a - b);
}
if (response.equalsIgnoreCase ("product"))
{
System.out.println (a * b);
}
else
{
noresponse = true;
System.out.println ("Starting again...");
}
}
while (noresponse = true);
}
}
You are using the assignment operator, =, so noresponse will always be true. The result of the assignment expression is thus true.
You want to check if it is true, so use the comparison operator ==:
while (noresponse == true);
or, because it's already a boolean:
while (noresponse);
Also, you may be getting a compiler error that noresponse may not have been initialized. You will need to make sure that it's initialized in all cases, and that something sets it to false so the loop will eventually end.
change while (noresponse = true); to while (noresponse == true);.
= is an assignment operation - where as == comparison.
Two errors:
The else applies only to the last if; so for any value, other that "product", noresponse becomes true and the loop goes on. Replace all your ifs from the second on with else ifs.
noresponse should be given the value false at the beginning of the loop.
There are 2 issues:
Currently you are looping while noreponse equals true. So to exit that loop, you need to setnoresponse to false when a particular condition is met :) I could give you the answer, but you should be able to figure it out with the info I've given you. (hint: at some point you need to set noresonse to false).
Also, you are setting noresponse to equal, rather than comparing it. You need to use == to compare.
So make while (noresponse = true); into while (noresponse == true);.
just change while (reponse = true) to while(reponse) and name the variable ..

Java won't loop properly

For some reason this program won't loop correctly, its supposed to wait for user input, then decide on weather or not it should loop.Instead, it skips the user input part, goes straight to deciding it needs to loop, then allows user input to be taken into account.
For example, it asks for a number, i type 5, then it says "would you like to go again?" "Please use either yes or no, case sensitive!" "would you like to go again?".After it has run that it will accept user input,I thought about using a sleep(2000),but I don't want it to just skip over and assume the user didn't put anything in.I am stumped! keep in mind this is my second day working with java. I am a newbie and this is only the 3rd program i am working on. I had this issue on another program but i managed to fix it just fine.However this one seems to not want to work in the same fashion despite the fact that i did framework exactly the same.
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
again = input.nextLine();
if (again.equals("yes")){
yon2 = false;
dateconverter.main(args);
}else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}else{
yon2 = true;
System.out.println("Please use either yes or no. caps sensative!");
}
}
} while (!(yon2 = false));
Java loops correctly. However, yon2 = false is an assignment and not a comparison.
Thus the loop is equivalent to:
do {
// ..
yon2 = false; // assign! :(
} while (!yon2);
So Java is doing exactly what it was told to do.
Now, with that out of the way, I believe the other issue is being confused about the variables usage. Consider this:
boolean askAgain = true;
do {
System.out.println("would you like to go again?");
if (input.hasNextLine()){
String again = input.nextLine();
if (again.equals("yes")){
// Finally done asking
askAgain = false;
dateconverter.main(args);
} else if (again.equals("no")){
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
} else {
// If we're here, we still need to ask again
System.out.println("Please use either yes or no. caps sensative!");
}
} else {
// no more lines! do something sensible
System.exit(0);
}
// Loop while we need to ask again!
// Note that the negative is removed
} while (askAgain);
However, taking a second to refactor this allows for something easier to read later and avoids the dealing with a flag entirely:
boolean promptKeepPlaying (Scanner input) {
while (input.hasNextLine()){
System.out.println("would you like to go again?");
String again = input.nextLine();
if (again.equalsIgnoreCase("yes")){
return true;
} else if (again.equalsIgnoreCase("no")){
return false;
} else {
System.out.println("Please use either yes or no.");
}
}
// no more lines
return false;
}
// somewhere else
if (promptKeepPlaying(input)) {
// restart game
dateconverter.main(args);
} else {
// exit game
System.out.println("good bye");
Thread.sleep(4000);
System.exit(0);
}
You've got a bug in your program. You've accidentally written an assignment instead of an equality test.
However, the real lesson here is that you should not be writing cumbersome == and != tests involving booleans. There are simpler, more elegant and less error prone ways of writing the tests. For example, assuming that condition is a boolean.
condition == true is the same as condition
condition == false is the same as !condition
!(condition == false) is the same as condition
condition == condition2 is the same as !(condition ^ condition2)1.
There is a real benefit in taking the time to write your code simply and elegantly.
1 - This is an example where == is more elegant ... but the ^ exclusive-or operator avoids the accidental assignment trap.

Categories