This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm writing a simple program and in it I need to get a user's input for yes/no (I'm using Scanner, UI, for this) like so:
System.out.println("Do you know the insulation capacity? (y/n) ");
String IC = UI.nextLine();
And that works perfectly fine, but I have trouble in the next section, where I check the string in an if statement:
if(IC == "y" || IC == "Y" || IC == "yes" || IC == "Yes"){ //four options of saying "yes"
System.out.print("What is the insulation capacity? ");
m = UI.nextDouble();
}else if(IC == "n" || IC == "N" || IC == "no" || IC == "No"){ //four options of saying "no"
findM();
}else{
System.out.println("Answer was not clear. Use y, n, yes, or no.");
checkM();
}
When I run the program, the else is always executed, even if IC is Y, y, Yes... etc.
Why is this the case and how do I get this to work?
Thanks,
-Justice
You should compare Strings with equals instead of ==. Otherwise, you'll be comparing the references, not their value, which is what you want.
Also, in this case equalsIgnoreCase may be helpful for you. You would only need 2 comparisons instead of 4.
Example:
if(IC.equalsIgnoreCase("y") || IC.equalsIgnoreCase("yes"))
You cannot compare Strings in Java using == operator. Use equals instead as for every Object-Type. In your case best solution is to use condition like ic.equalsIgnoreCase("y") || ic.equalsIgnoreCase("yes")
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I'm a total beginner at Java and am struggling with making a simple card game where you choose between values "red" and "black". Can anyone see what's wrong?
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
if (guess == s)
System.out.println("Correct");
else
System.out.println("Wrong");
} while (guess != s);
In Java Strings are an object, when comparing Objects:
== tests for reference equality (whether they are the same object).
.equals() tests for value equality (whether they are logically
"equal").
This is further explained in How do I compare strings in Java?
On the other hand, char is a primitive data type and on primitive types == tests for value equality. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Edit - Regarding case:
In Java you have the method "equalsIgnoreCase" to compare two Strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and it represents an equivalent String ignoring case, else false.
So, you've got a couple of problems here:
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
//The problem is that you're using reference comparison, but that's not the only issue you 'will have', you're only checking raw input vs upper case 'R'
//and 'B' so you 'need' (you can handle this with lower case or alternative, too) to change this to `.toUppercase()`.
if (guess == s)
System.out.println("Correct");
else
System.out.println("Wrong");
//The same problem is happening here:
} while (guess != s);
New code:
String guess;
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
char answear = r.nextBoolean() ? 'R' : 'B';
String s = String.valueOf(answear);
do {
System.out.println("Guess the color of the card - (R)ed or (B)lack?");
guess = keyboard.next();
if (guess.toUpperCase().equals(s))
System.out.println("Correct");
else
System.out.println("Wrong");
} while (!guess.toUpperCase().equals(s));}
When you use ==, you're comparing references.
To compare text (string type), you should use .equals().
You should also make sure that the case upper/lower is catered for to prevent errors, as r is not equal to R.
Basically, don't use == for strings, that's only good for primitive data types or basically anything that isn't an object. Because that points to the reference of the string and compares if they're equal (Basically testing if they're the same variable not the same string contents. In the case of strings you want to use .equals(), Usually I put a ToUpperCase() statement in there like so:
if(guess.toUpperCase().equals(s.toUpperCase()))
to get rid of case sensitivity because it just makes everyones lives easier but I know thats not a part of the question
tldr: Use .equals when comparing strings, otherwise it points to the objects of the string and not the contents.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Consider my code below:
System.out.println("Insert your inventory");
for (int i = 0; i<20;i++) {
System.out.print(i+1+".");
if (inventory[i] == "N" || inventory[i]=="n") {
break;
}
inventory[i] = s.nextLine();
}
How can I exit from this loop if the user enters 'N' or 'n'?
You're comparing string with == operator. It does not yield correct result because your constant string "N" and your input "N" do not have same reference/pointer.
You have to use equals() to guarantee the correct compare result between strings.
Replace
if (inventory[i] == "N" || inventory[i]=="n")
With
if (inventory[i].equals("N") || inventory[i].equals("n"))
You should compare your String variables with the .equals() method instead of the == operator.
An explanation about why this is important can be found here on StackOverflow.
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
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to ask user to insert operator and get the answer till user enters keys other than +,-,* or \ .I did the program like this.But it will not work properly.Its looping even for other keys.What is the problem with the coding?
public static void main(String Args[]) throws IOException
{
InputStreamReader myrdr=new InputStreamReader(System.in);
BufferedReader myBfr=new BufferedReader(myrdr);
Scanner myScanner=new Scanner(System.in);
String mathOp;
float Res,Num1,Num2;
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
Res=0;
while(mathOp!="+"||mathOp!="-"||mathOp!="*"||mathOp!="\\")
{
System.out.print("Enter number one: ");
Num1=myScanner.nextInt();
System.out.print("Enter Number Two: ");
Num2=myScanner.nextInt();
switch(mathOp)
{
case "+":
Res=Num1+Num2;
break;
case "-":
Res=Num1-Num2;
break;
case "\\":
Res=Num1/Num2;
break;
case "*":
Res=Num1*Num2;
break;
default:
{
System.out.println("Programme Exits");
return;
}
}
System.out.println("Answer is : "+Res);
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
}
}
Don't use == (which compares if the 2 operands are the same String object, which they aren't), use equals() (which compares if the contents of the 2 String objects are the same).
But better yet, simplify your code to this:
while (!"+-*\\".contains(mathOp))
btw, divide is usually a normal slash /, not a backslash \.
Yoy have to use someting like that
while((!mathOp.equals("+"))||(!mathOp.equals("-"))||(!mathOp.equals("*"))||(!mathOp.equals("\")))
First of all you should know the proper use of || and &&
True || False returns true
True || False || False || False returns true,one True is enough to make the condition return true no matter how many false you have
So in your case you are saying that if the input is different from one of them than let it proceed,so if you have + it will enter since + is different that -. You should instead use &&.
True && False returns False
True && True && True && False returns False. One False is enough to return False no matter how many True you have.
If you use && you would be telling the condition to return true only if all the sub-conditions are true,i.e it is different than + and different than - and different than * and different than .
Moreover, replace your "+" by '+' because the latter it is a character while the first is a string. == can be used only on characters,numbers and boolean values. To compare Strings you should use .equals("x")
Make your while loop like this
while(mathOp.equals("+") || mathOp.equals("-") ||
mathOp.equals("//") || mathOp.equals("*"))
Use String.equals() to compare string in Java, not == or !=. To explain more, you shouldn't use == or != while comparing String values in Java because they check for equality for the values in the right and left operands. i.e a memory address in case of String objects ,which will not be equal for two different objects. You can make use of == and != with primitive datatypes and compile time constants. There is also a concept called String constant pool which has the compile time String constants created by using assignment operator like String new = "new"; without using new operator during object creation which can be compared using == or !=.
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()