This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
m trying to write a super simple piece of code which asks "are we nearly there yet" if the user inputs yeah they get the answer "finally" if the user says anything other than yeah the computer keeps asking are we nearly there yet?
for some reason when I run the code below even if I type "yeah" after the first prompt the computer just keeps printing are we nearly there yet? and can't get through the loop.
import java.util.Scanner;
class FirstAttempt {
public static void main(String args[]) {
Scanner s= new Scanner(System.in);
String a =" ";
System.out.println("are we nearly there yet?");
a = s.next();
while ( a != "yeah" & a != "Yeah")
{System.out.println("are we nearly there yet?");
s = new Scanner(System.in);
a = s.nextLine(); }
System.out.println("finally");
} }
The issue is just in the way you wrote the condition in the while.
The application doesn't go in the loop, because your condition is always false. Basically, that's because you are not comparing the values of the String objects, but the values of their instances.
In Java, you must compare one String object with another by using equals and not with operators != or ==
Plus, I suggest that you use &&, instead of &. The first one is short-circuiting, which means that the first condition is evaluated, and only in case it's true the second one is also evaluated.
However, there is a more efficient way to do that. Look at this:
while ( !a.equalsIgnoreCase("yeah")) )
To test if strings are equal you need to use equals:
while ( !(a.equals("yeah") || a.equals("Yeah")) )
& is a bitwise operation -- you probable want the logical operations && and ||.
Also, no need to create a new Scanner inside the loop. Just keep using the one from the top of the main method.
The & operator, otherwise known as 'bitwise and' will evaluate all conditions regardless of whether the first condition is true or false. So while the input "yeah" makes the first condition false and thus loop-breaking, the second condition is still evaluated to true and keeps the loop going. You should use &&
You have to change
while ( a != "yeah" & a != "Yeah")
to
while ( a != "yeah" || a != "Yeah")
as it can't be both at the same time
Related
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 10 months ago.
I am within my first year of CS and near the end of my first Java themed course so I'm not quite sure how to find the answer to my question myself.
While writing some code for a project I created my input scanner as:
Scanner scanner = new Scanner(System.in);
I am taking user inputs as strings via a variable assignment:
String userInput = scanner.nextLine();
the user should only be entering strings of char "1" - "6" and "q" (to quit app)
What I'm using that works currently is as follows:
userInput = scanner.nextLine();
while (!appQuit) { //So long as user doesn't quit application
if (userInput.equals("q")) {
appQuit = true;
}
else if (userInput.equals("1")) { //Menu selection for intake a new dog
intakeNewDog(scanner);
displayMenu();
userInput = scanner.nextLine();
}
//removed "2" - "6" for brevity
else {
System.out.println("Not a valid input");
displayMenu();
userInput = scanner.nextLine();
}
}
The only way I found to check equality was the userInput.equals() function.
When I originally wrote it I tried using:
if (userInput == "1") { code }
but it would never successfully compare values as I thought it would.
Any insight into why one method works over the other? Or where I should be looking for these answers?
-Jonesy
The == equal operator compares the object references where the equals function compares the value.
For primitive types and enums the == equal operator compares the value.
An exception happens for comparing strings in a switch case statement since it internal uses the equals method.
As a rule of thumb, always use equals comparison for String. There maybe is, but i have not seen a case where reference comparison was important.
https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html
Also interesting:
What makes reference comparison (==) work for some strings in Java?
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. You can override the equals method to do more specific things, but that's the just of it.
This is literally the first thing that appears if you search java == vs equals in google.
While you might be trying to compare two strings, the operator == does not behave in java as it does in other languages.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
First off, I know this might have been answered SOMEWHERE but I can't seem to search for the correct terms to get an answer. Also, I'm pretty new to coding, and obvious here, so this probably won't be the best written 'question'.
Quick backstory: I'm coding a sorting game in BlueJ(I know... shitty, but it's what we are learning in school), and for a method I'm creating for any yes/no questions I need isn't working properly. At first, I was having an issue with it allowing to to have the user input save as a String, now I'm having an issue with that String used in the if-else statement parameters. This is what I have right now:
public void userAnswer(int method) //used for yes/no questions
{
System.out.println("Please type 'y' for yes and 'n' for no.");
String answer = keyboard.next();
answer.toLowerCase();
System.out.println(answer + "worked");
if(answer == "y")
{
System.out.println("worked2");
if(method == 0)
completeOrNot();
if(method == 1)
usersMove(theArray);
}
else if(answer == "n")
{
System.out.println("worked3");
System.out.print("\n");
}
}
I'm completely stuck as to why it's not moving into the if-else statement. I test to see if it would print the String, and it will, but it won't convert it to lower case. I just don't know what to do. Any and all help would be appreciated!
When comparing Strings in Java, use the equals() method. Otherwise, you compare their memory locations if you use ==.
"hi".equals("hello") returns False
"hello".equals("hello") returns True
Don't use == to compare strings. use equals:
answer.equals("y")
Strings in Java are objects - you need to evaluate with the equals method for equality, not the == operator for reference identity:
if ("y".equals(answer)) {
// code
} else if ("n".equals(answer)) {
// code
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I wrote a simple program which prompts the user to enter a sentence, word, or number, and then prints input is art. I put the program on an infinite loop so that the prompt would repeat. However, now I'm trying to add a way to quit by saying if (input == "quit") break; however it does not seem to be working. It just continues the infinite loop. Here is the full code:
import java.util.Scanner;
public class Art
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String a;
for ( ; ; )
{
System.out.println("Please enter something: ");
a = input.nextLine();
if (a == "quit") break;
System.out.print("\n");
System.out.println(a + " is art.");
System.out.print("\n");
}
}
}
Any help would be lovely, thanks!
Use input.equals("quit").
The == is used to check whether two objects are the exact same instance - the same thing in memory -which the typed word and the constant string "quit" are not. Two instances of "quit" were created: one typed by the user, and one constant in the program.
The equals() method is used to compare whether two objects are equal in whatever way equality is defined for them. For strings, that would mean having the same text.
The difference between == and equals() is really fundamental in Java, so you should go over it. Here's a good SO post on the topic. Once you start creating your own classes, you will probably be implementing equals() methods for them. For that reason, make sure to go over the equals() / hashCode() contract as well.
looks like the a == "quit" is the problem. Compare strings using equals()
if("quit".equals(a)) {
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I have been having difficulties using nextLine() to get a string, and then use it as a test condition (either in an if statement or a while loop). Looking at the println(), it seems as if the String is correctly assigned to the variable 'repeat' but then the test condition fails for some reason. Banging my head on the wall, bleeding from my forehead. Please help.
import java.util.Scanner;
public class potpie {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String repeat = "yes";
System.out.println("Type in yes");
repeat = input.nextLine();
System.out.println("If repeat is now yes, print yes: " +repeat);
if(repeat == "yes"){
System.out.println("It worked");
} else
System.out.println("it failed");
}
}
You should use equals. == provide you reference equality and equals provide you value equality.
if("yes".equals(repeat)){
instead of
if(repeat == "yes"){
I would advice you to get eclipse/net beans and start debugging or a simple search would have resulted in the answer
Java Debugging with Eclipse - Tutorial
if(repeat == "yes"){
should be
if(repeat.equals("yes"){
(or)
if("yes".equals(repeat){
Every day we see this question lot of times, simple search could have provided you sufficient information.
== equals for primitive comparison (reference equality). equals() is for String (or) Object comparison (object content equality).
Sometimes == should be used for objects, but what it is actually comparing is whether a and b are literally the same object (have the same address in memory). As the others have said, you are comparing content in this situation, so you use .equals()
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I am writing a program that should close the console if the user input the String "end'.
The program always performs the else loop even if the user inputs "end". I'm wondering why the program is not getting into the if part of the loop and shutting down.
Scanner scan = new Scanner(System.in);
while(true)
{
String num = scan.nextLine();
if(num == "end")
{
System.exit(0);
}
else
{
System.out.println("hi");
}
}
You're using == instead of "end".equals(num)
Don't use == for equality of string as it compares the objects not the string itself.
Use num.equals("end") or num.equalsIgnoreCase("end") if you want to be able to type end or END
I would not use "end".equals(num), although considered better from a performance perspective in most cases, it does not clearly state the business requirement and it is more important to make it more readable.
But be aware of num being null, if that is possible, num.quals("end") could throw an exception and you should write if (num!=null && num.equals("end")) { ... }
Note that "end".equals(num) does not need the null check, but I still believe this is not very readable, so I would go with if (num!=null && num.equals("end")) { ... }
For testing equality between strings, you should use equals() instead.
if(a.equals(b)) and so on.
This should help you out: http://leepoint.net/notes-java/data/expressions/22compareobjects.html
In Java, you test equality of strings with:
string1.equals(string2);
So in this case, it would be:
num.equals("end");
Or to avoid an exception of type NullPointerException:
"end".equals(num);
num refers to the object, so num == "end" should never be. You want num.equals("end")
Please do not use comparison (==) operator when comparing objects in Java. Use equals(Object) instead.