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

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.

Related

I can't loop my code whenever condition fails. It just prints both blocks of code if the user input is true

I am a beginner at java and I want to loop this all over again but I don't know how. I've tried a while loop but it doesn't work really well and it prints both blocks of code. What should happen is when I type "quit, Quit, or QUIT", it should terminate. What happens instead is that it also prints the message "failed to terminate the program". What should I do? I've also tried an if statement which works fine but I don't know how to loop it if the condition fails.
import java.util.Scanner;
public class fortytwo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi there!");
String quit = scanner.next();
while (quit.equals("quit") || quit.equals("QUIT") || quit.equals("Quit")) {
System.out.println("You terminated the program");
break;
}
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
scanner.close();
}
}
You are using a loop without a need for it. Also break only exits the loop, but continues execution after the loop. Replace the while with an if/else:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Hi there!");
String quit = scanner.next();
if(quit.toLowerCase().equals("quit")) {
System.out.println("You terminated the program");
} else {
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
}
scanner.close();
}
This does not prompt for input again which your second output hints at, but neither does your code.
The condition of the loop is to check while quit is NOT equal to "quit" (regardless of the case), so the message "You failed to terminate the program..." should be printed in the loop body until appropriate command is entered.
Also, assignment to quit may be omitted, and the method equalsIgnoreCase is recommended to invoke on the constant/literal value because in general case it helps avoid NullPointerException.
while (!"quit".equalsIgnoreCase(scanner.next())) {
System.out.println("You failed to terminate the program.\n To quit, type (quit), (Quit), or (QUIT)");
}
System.out.println("You terminated the program");

why does it not break out of the loop whatever is the input

whatever the input is, it never breaks the loop i tried.
i tried with the switch same result; i tried with only one condition (!answer.equalsIgnoreCase("y")) without the OR and it worked but nott with two conditions.
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
//checking if the dog is barking
System.out.println("is the dog is barking ?");
String answer;
do {
System.out.println("write 'n' for no and 'y' for yes");
answer = scn.next();
} while( !answer.equalsIgnoreCase("y") || !answer.equalsIgnoreCase("n"));
boolean dogBark=answer.equalsIgnoreCase("y");
i expect it to finish the while loos as soon as i enter 'y' or 'n' but its asks me for input over and over.
While answer is not yes or answer is not no?
If it's yes, then it isn't no. If it's no, then it isn't yes. So the condition is always true and it loops.
You probably want to use the ! operators.
while( !answer.equalsIgnoreCase("y") || !answer.equalsIgnoreCase("n"));
The issue is occurring because the do-while loop is checking both conditions with the OR statement.
Think about it like this, if Answer equals "Y" that condition is met to break the loop but the OR condition "N" is still active therefore the loop will continue.
The do while is only checking to ensure one of the conditions above is false before continuing the loop.
To fix this replace the || with && and the loop will break if either Y or N is entered as the loop will only continue if both conditions are false.

How to terminate while loop once response is correct?

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.

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 ..

Categories