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.
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 9 years ago.
I am relatively new to coding in general and have run into an issue, I've looked everywhere for help but I cant find this issue. It would be greatly appreciated if someone could tell me why the string "s" doesn't ever equal the string "temp" even if I type the correct number in.
String s = null;
do{
s = (String) JOptionPane.showInputDialog(null, "Select a card to check for (Jacks = 11, Queens = 12, Kings = 13)", "Player's Turn", JOptionPane.PLAIN_MESSAGE, null, null, "Pick a card");
System.out.println(s);
for(int x = 0; x < PlayerCards.size(); x++){
String temp = PlayerCards.get(x).getFace();
if(s == temp){
playerhas = true;
}
}
if(s == null || playerhas != true){
JOptionPane.showMessageDialog(null, "Please pick a card you have.", "Error", JOptionPane.INFORMATION_MESSAGE);
}
}while(s == null || playerhas != true);
Strings work like objects in Java.
If you do stringA == stringB this will always return false since stringA and stringB are different objects.
Comparing strings needs to be done using stringA.equals(stringB) and this should return true (if the values match).
Chris 7 you're right that strings are objects but new compilers do some optimizations on those strings and it could happen that stringA == stringB are equal but it's not promised. So you should always use the string comparison functions (String.equals or String.equalsIgnoreCase).
By the way you can optimize your code. Use functions that implement only one feature and not more... e.g. externalize your function that checks if one has the card or not:
boolean playerHas(String s) { for (PlayerCard card : playerCards) { ... } return false; }
The
==
operator compares objects, while the
.equals
function compares object values.
String foo = "loremipsum";
String bar = "loremipsum";
System.out.println(foo == bar);
System.out.println(foo.equals(bar));
this ==compare bits, it works with primitive variable because when you declare a primitive variable it saves its value in bits, but when you declare a reference variable it only works if two reference are the same.
See this example:
String object1 = new String("hola");
String object2 = object1;
System.out.print(object1==object2);
This will return true because object2 have the same bits that point to the same object on heap, because they were copied when i said:object2 = object1
So if you want to compare objects by value instead by reference you have to use: equals() method.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm currently working on a financial planning app for class but I cant get a loop with a condition inside it to work. It just keeps looping despite the condition - it's almost as if the condition is being ignored completely.
Here's my code - please help!
while (true){
Scanner scanVar = new Scanner(System.in);
System.out.println("\nEnter expenditure item: ");
String myString = scanVar.nextLine();
Scanner scanVar2 = new Scanner(System.in);
System.out.println("\nEnter expenditure value: ");
double myDouble = scanVar2.nextDouble();
expenditureMap.put(myString, myDouble);
Scanner scanVar3 = new Scanner(System.in);
System.out.println("\nAnother item? ");
String myString2 = scanVar3.nextLine();
if (myString2 == "yes") {
continue;
}
else {
break;
}
}
Many thanks,
Dylan
You really want to be using mystring2.equals("yes") (or even better, "yes".equals(mystring2) )
The == operator on objects tests for them being the identical instance, not the same string values....
String a = new String("yes");
String b = new String("yes");
a == b => false
a.equals(b) => true
If you are using the == operater it is comparing if the object references match. You should use the equals operator
if (myString2.equals("yes"))
change the condition as follows and then try:
if (myString2.equals("yes")) {
You shall use equals ... check this post
How do I compare strings in Java?
reference comparison means checking if both objects have the same address in memoery
value comparison means checking the value inside the objects
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
How do I know if String letter is equal to char array
String[] choose = {"a","d","t","b","s","f","x"};
String check;
boolean error = false;
System.out.print("Enter");
Scanner sn = new Scanner(System.in);
check = sn.nextLine();
for (int i = 0 ; i < choose.length;i++){
if(choose[i] == check){
System.out.print("you entered" + choose[i]);
break;
}
}
What I did is this it didnt confirm I input letter a but "you entered" didnt show up.
You cannot test strings for equality using ==. That only compares references (memory addresses). You need to use String#equals(Object). In general == is most certainly what you don't want if you are testing for equality, unless you are checking to see if two variables are pointing to the same instance. This is rarely the case, since you are usually interested in testing values for equality.
So what you need to do is:
if(choose[i].equals(check)) {
...
}
You are trying to compare strings with ==, which only compares the references, but not the values. What you want to use is
if(check.equals(choose[i]))
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
public void play () {
int anInteger;
//guess return code
int code;
while (true) {
String input=null;
input = JOptionPane.showInputDialog("Please enter an integer");
if (input == "-1") {
//JOptionPane.showMessageDialog(null, input);
System.exit(0);
break;
} else {
if (input==null) {
System.exit(0);
} else if (input.isEmpty()) {
continue;
} else {
anInteger = Integer.parseInt(input);
code = this.oneGuess (anInteger);
//JOptionPane.showMessageDialog(null, anInteger);
}
}
}
}
I want, if the user enter -1, show the program will not prompt the message box any more. Above is the code I have come up with, so far. Why it doesn't work?
String comparisons does NOT work with "==" operator, use "String.equals(Object)" function
input.equals("-1");
Better way would be
"-1".equals(input);
as it also takes care of null input
You are comparing strings, which are objects, with the == operator, which checks whether two object references refer to the same object instance. Instead you should use the equals method for comparing them.
There is a difference between comparing with == and equals. The first compares pointers, the latter contents. That is probably your issue.
You compare Strings with ==, which creates a problem. You can have many different String-Objects which all show "-1". The == tests, if you have exactly the same object on the left and right side. You want to know, if the objects on the left and right sie have an equal content.
Better try
input.equalsIgnoreCase("-1");
EDIT: To answer the comment: input.equalsIgnoreCase("-1") is the same as input.equals("-1") in the case of "-1" as there are no uppercase/lowercase letters in "-1". However, I prefer equalsIgnoreCase in the case of Strings, because it is defined on String, rather than on Object. Still, as the equals-definition is overridden for the String class, it works too in this example and "ignoreCase" is not needed.