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]))
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 4 years ago.
I am trying to check if a playlist is simple or master by an index value. My problem is when I put the (True) URL it still returns a false statement "This is a simple Playlist".
Any tips on how I can fix this ?
String output = getPlaylistUrl(input);
String mediaRecord = output.substring(399);
String lastRecord = "gear4/prog_index.m3u8";
if (mediaRecord == lastRecord) {
System.out.println("This is a master playlist");
} else {
System.out.println("This is a simple playlist");
}
In Java, strings can not be compared for equality using ==, because == compares two instances, not the content. So unless s1 and s2 are actually the same instance, s1 == s2 will never return true.
You need to use equals(...) to compare two strings for equality.
if (mediaRecord.equals(lastRecord) { ... }
In order to compare Strings you need to use .equals and not ==. Using == compares references and not values
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I´m having trouble with the while statement. I´ve narrowed it down to my use of the "!=", because if I try it with "==", then the program works, except opposite to how I want it to. What do I use to make it so that if the user types in "v", then it won´t display the user´s input, since there´s no such thing as "!==" :)
Scanner scannerUi = new Scanner(System.in);
String userInput = scannerUi.nextLine();
while (userInput != "v") {
System.out.println(userInput);
userInput = scannerUi.nextLine();
}
use
while (!userInput.equals("v")) {
System.out.println(userInput);
userInput = scannerUi.nextLine();
}
I think that u need to compare string not on reference equality as u do it but on value equality.
So, if u want to compare your current string with some other (such as "v") just use:
userInput.equals("some_string")
Using "==" u will compare strings on reference equality, and using "equals()" u will compare strings on value equality
you should always use equals() method for compairing the strings, because equals method examine the content and == method examine the references.
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 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.