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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
public static void processtrans()throws FileNotFoundException{
Scanner input = new Scanner(transFile);
String line = input.nextLine();
double dollar = 0;
int transNum = 1;
while (input.hasNextLine()) {
int Space = line.indexOf (" ");
int Space2 = line.indexOf (" ", Space + 1);
String action = line.substring(0,Space);
if (action == "ORDER"){
int Space3 = line.indexOf (" ", Space2);
String isbn = line.substring(Space + 1, Space2);
int num = Integer.parseInt(line.substring(Space2 + 1, Space3));
int custNum = Integer.parseInt(line.substring(Space3 + 1));
System.out.println("Number= " + num);
System.out.println("Customer number= " + custNum);
}
line = input.nextLine();
}
}
While I was debugging this code since it compiles but doesn't print anything I saw that it reads the first line of input separates the first word and puts it in the String action but after that it sees if action is "ORDER" or not then skips everything to the line I don't understand why can someone help me?
Use equals to compare strings
if (action.equals("ORDER")){
When you use == , you are comparing the String object instead of the actual string.
As mentioned in the comments, here is a great reference for this
The == operator in java compares objects for identity (i.e., it returns true if they both reference the same area of memory). In order to compare objects for equality (i.e., return true if they have the same value), you should use the overloaded equals(Object) method:
if (action.equals("ORDER")) {
// ...
}
In Java == check whether both reference referring same object or not in memory. To check two string objects are meaningfully equal with their content, you have to use equals() method like below
if (action.equals("ORDER")){
In Java, using == on a String object actually returns true if both are references to the same Object.
In order to check for String equality, there are a few ways to do this.
Objects have an equals(Object o) method that will usually allow you to compare the objects values and see if they are equal.
In the case of a string,
String foo = "foo";
String bar = "foo";
if(foo.equals(bar)) {
// Hooray
}
However there is another way of going about this. Some recommend to use a string literal for the test to avoid a NullPointerException.
For Example:
"foo".equals(bar);
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am using Java and have been trying to split my string input into 3 parts. For example, my input will be "AND 1 1", and I am expecting it to go into my if-loop where the condition is parts[0] == "AND". But this is not the case, and I am not sure why.
My code is listed below
Scanner stringInput = new Scanner(System.in);
String input = stringInput.next();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
In Java you can not be sure that the string is the object you think it is. For this reason, you should not use == to compare objects, but use the equals function.
if (parts[0] == "AND")
should be
if (parts[0].equals("AND"))
Strings are immutable, so the functions will always return new strings, when they have to do something on them. For this reason, using == will only work in some particular cases, but never when you process them.
You are using stringInput.next() which will not read spaces. So that is the problem.
Use stringInput.nextLine() instead of stringInput.next()
String input=stringInput.nextLine(); is correct when you are working with text that contains space.
Here is the edited code.
Scanner stringInput = new Scanner(System.in);
String input = stringInput.nextLine();
System.out.printf("%s\n", input);
String[] parts = input.split(" ");
if (parts[0] == "AND") {
if (parts[1] == parts[2] && parts[1] == "1")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
else {
if (parts[1] == "1" || parts[2] == "0")
System.out.printf("1\n");
else
System.out.printf("0\n");
}
You probably might have got an ArrayIndexOutOfBoundsException
You are using the String.split() method in correct way. The parts[0] also contains the desired "AND" after using the method.
But the problem is you are checking equality of two strings using "==" instead of equals method. When you use == then it checks whether they are same reference of string while the equals method check the values of the string.
So your checking should be something like this
if (parts[0].equals("AND"))
Use
parts[0].equals("AND") to check equality of `String`
Just to complete the Devolus answers (I can't put comments in comments yet U_U)
== compares the references, it means that is only true if two variables are pointing to the same object
e.g.
Object a = new Car()
Object b = a
Object c = new Car()
(a == b) //true
(a == c) //false
a.equals(b) //true
a.equals(c) //true
Try this piece of code:
if (parts[0].toString().equals("AND")){
if (parts[1].equals(parts[2]) && parts[1].equals("1"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}else {
if (parts[1].equals("1") || parts[2].equals("0"))
System.out.printf("1\n");
else
System.out.printf("0\n");
}
There are several issues:
as JavaTechnical pointed out, you should use stringInput.nextLine() vs stringInput.next()
as everyone pointed out, use .equals() vs ==, here's a thread explaining why: Java String.equals versus ==
test against a known vs an unknown, reorder your test like so "AND".equals(part[0]) should shield you from null pointer
Try using .substring(), for example:
String a = "AND 1 1"
b = a.substring(1,3)
c = a.substring(4,5)
System.out.println(b)
System.out.println(c)
Would print "AND" then "1"
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am still new to Java. I am trying to create a program where users must answer a multiple choice quiz. The users will input their answer and these inputs will be formed into an array. Then I plan on using a for loop to compare the user's answers array to the array of correct answers to tell the user if they are right or wrong.
However it seems that i am not properly comparing the 2 arrays in my if statement. Every time I run the program, it goes straight to the else statements.
My hunch is that the scanner class does not actually store the value?
Can anyone help?
Part of code below:
//Above this section is just a collection of "System.out.println" statements that state questions and answers the user choose from.
int x;
String answers [] = {"a", "a", "b"};
//answers array has the correct answer
Scanner in = new Scanner(System.in);
String answerEntered [] = new String [5];
//user input will be in this arra
for(x=0 ; x<3 ; x++)
{
System.out.print((1+x)+". ");
answerEntered[x] = in.nextLine();
}
for( x=0; x<3; x++)
{
**if(answerEntered[x] == answers[x])
{
System.out.println("For Question "+(x+1)+", you are Correct!");
}**
//This if section does not seem to work. Every time i run the code it automatically goes to the else statement.
else
{
System.out.println("The correct answer for Question "+(x+1)+" is: "+answers[x]);
}
}
In Java, String aren't primitive values, you have to use String.equals() to compare strings
so, change this:
if(answerEntered[x] == answers[x])
to
if(answerEntered[x].equals(answers[x]))
I would also suggest that you check for nullability and ignore case, so:
String answer = answerEntered[x];
boolean isAnswerCorrect =
answer != null &&
//remove trailling spaces and ignore case (a==A)
answer.trim().equalsIgnoreCase(answers[x]);
if(isAnswerCorrect){
For String or any object-equality test in Java, you should almost always be using equals. The == operator only compares references when used with objects (but will work the way you expect it to with primitives like int, boolean, etc); that is, it checks to see if the operands both point/refer to the same object instance. What you're interested in doing is comparing the contents of the String instance, and equals will do that for you:
if(answerEntered[x].equals(answers[x])) {
...
}
For String comparison, you need to use equals instead of ==, which for non-primitive data types, such as String, compares their references, not values.
String a = "foo";
String b = "bar";
if (a.equals(b))
{
//doSomething
}
The problem is in the comparison :
String a = "foo";
String b = "bar";
if (a.equals(b))
//doSomething
AS it Has been answered before.
Extra information, in the for loop of the if / else you are looping only the first 3 positions, not the 5 that exists in the answerEntered array.
Cheers
Use .equals to compare strings. equals compares the values, where == compares the reference
.
In Java, == comparison compares reference identity, means the two things you compare must be the same object. Two objects with the same values are treated as different.
You statement:
if(answerEntered[x] == answers[x])
The answerEntered contains string that is different with any string in answer even if they have the same value.
Java uses Object's .equals method to compare by value, i.e. Two objects are equal as long as they have the same value.
Changing:
if(answerEntered[x] == answers[x])
to
if(answerEntered[x].equals(answers[x]))
should solve the problem.
Also, as answerEntered contains user inputed value, you'd better pre-process it before using it. For example, user might put answer "a " with spaces at the end. You might want to get rid of those spaces as well.
Otherwise "a " will be treated as an incorrect answer.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I have two identical strings, one in an array and one in a String variable. When I compare these IDENTICAL strings I get false every time. I have debugged and debugged, but I get the same result every time. Here is the code in question
String temp = ""+(num1*num2);
Boolean equal = temp == answers[i];
if(equal) {
correct[i] = true;
num_correct ++;
}else{
correct[i] = false;
}
Again, I have debugged every minor detail of this program and I am 101% sure that the strings are IDENTICAL. Why is Java returning false on comparison?
When you use the == operator in Java with objects, you are attempting to compare object references. That is, is this object handle pointing to the EXACT same object as this other object handle. Unless the strings are interned, this will not work.
Use String.equals(Object) instead:
Boolean equal = temp.equals(answers[i]);
You are doing reference comparison, not value comparison. When you use the == operator its checking to see if the references are equal, and they aren't. If you want to check whether the values are equal use the equals method.
boolean equal = temp.equals(answers[i]);
== in java for strings is comparing to see if they are the same object, not the same string value. You should use .equals instead which will compare the value. == works sometimes because the strings can be interned and refer to the same object via reference even if created seperately through the same literal (so string b = "Hey" and string c = "Hey" end up being the same object in the background because "Hey" got interned to a hidden string object).
As others have shown you should use equals.
But I would also use the booleanValue of the Boolean object.
Here is your code correctly done
String temp = ""+(num1*num2);
Boolean equal = temp.equals(answers[i]);
if(equal.booleanValue()) {
correct[i] = true;
num_correct ++;
}else{
correct[i] = false;
}
Does this help?
Boolean equal = (temp == answers[i]);
I'm not sure that would be an issue, but I always enclose my conditions in parenthesis.
I am completely stumped with this one . . .
If I call the function below with the following:
Search(SearchTextField.getText()); // (Fiberglass was entered)
Search("Fiberglass"); // hardcoded
I get the following results:
Fiberglass 10 Not Here
Fiberglass 10 String found!
Same String is passed with the same length, different results. How can this be?
Yes I've trimmed it on both sides of the == with no luck.
I am loosing my mind, any help would be appreciated.
Test[] array = new Test[3];
array[0] = new RowBoat("Wood", "Oars", 10);
array[1] = new PowerBoat("Fiberglass", "Outboard", 35);
array[2] = new SailBoat("Composite", "Sail", 40);
public void Search(String searchString) {
boolean found = false;
System.out.print(searchString + " " + searchString.length() + " ");
for (int i = 0; i < array.length; i++) {
if (searchString == array[i].getBoatMaterial()) {
found = true;
break;
}
}
if (found) {
System.out.println("String found!");
} else {
System.out.println("Not Here");
}
}
Use the .equals() method when you're comparing Strings. Do not use ==
equals() will compare the actual String content, no matter where the String resides in memory.
if (searchString.equals(array[i].getBoatMaterial())) {
Since String variables are references in Java, when you code
if (searchString == array[i].getBoatMaterial()) {
What you are actually doing is comparing two pointers. It just so happens that when you hardcode the same string in multiple places in your program the compiler reduces it to one instance (since Strings are immutable) and reuses it. This is why using a hardcoded value succeeds, since both pointers point to the same value. However, when the search string is not the same hardcoded "Fiberglass", the two strings are at different locations and the comparison fails. To compare two strings use the String.equals(String) method instead.
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal.