This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I am a beginner in android studio. I am working on a quiz app . The app should check for two strings to be compared and give the correct answer. But comparing the two strings (even though if they are same) is not giving the correct output. Instead it is directly going to the final return statement in the code. Here’s the code:
// ...
EditText Answer1 = (EditText) findViewById(R.id.answer1);
String ans = Answer1.getText().toString();
Log.v("MainActivity", "City name :" + ans);
String answer= String.valueOf(Answer1);
// ...
public String YourAnswers(String ans, boolean isDT, boolean isHC, boolean isBO,String answer) {
String Message = "1.:You answered \n"+ans+ "\n" +ques1(answer);
Message = Message + " \n 2.: \n" +question2(isDT,isHC,isBO) ;
return Message;
}
public String ques1(String answer) {
if (answer == "Jefferson City"){//||ans=="Jeff City"||ans=="Jeffcity"||ans=="Jeffersoncity"){
return "correct";
}
else if(answer =="Jeff City") {
return "correct.";
}
else if(answer =="Jeffcity"){
return "correct..";
}
else if(answer.equals("Jeffersoncity")){
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
When it enters into ques1(), it is directly going to the last statement i.e. return "Sorry,but the correct ans is Jefferson City";. When I enter the correct answer too it is returning the above mentioned line.
Any ideas as to why this might be happening?
"==" is not the correct way to compare contents of a String in java.
use string1.equals(string2)
Use .equals() throughout instead of ==.
However try this code to allow for any capitalization of answer using toLowerCase():
import java.util.Arrays;
...
...
String[] answers = {"jefferson city","jeff city", "jeffcity", "jeffersoncity"};
if(Arrays.asList(answers).contains(answer.toLowerCase())) {
return "Correct";
} else {
return "Sorry,but the correct ans is Jefferson City";
}
Background
There are two common methods used in order to compare two strings in Java. In your example, rather than making use of one of them, you’re using == which is an equality operator—these, you can’t use to check for equality on Strings.
The first method you may use is equals, located on the String. This will check and see if all characters contained by the String are exactly the same—that is, it also makes sure the String you’re giving it has the same letter case as the one you’re comparing it to.
Here’s an example:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns false
The second method you may use is equalsIgnoreCase, also located on the String. This will return true if the Strings compared are the same, but don’t give into account if they’re of different cases—it doesn’t care.
Let’s repeat the previous example and see what happens:
"Hello, world!".equals("Hello, world!"); // ‘equals’ returns true
"Hello, world!".equalsIgnoreCase("hello, world!"); // ‘equals’ returns true
See how both returned true this time around?
Solution
With all this in mind, we can go ahead and fix your code up:
public String ques1(String answer)
{
if (answer.equals("Jefferson City"))
{
return "correct";
}
else if(answer.equals("Jeff City"))
{
return "correct.";
}
else if(answer.equals("Jeffcity"))
{
return "correct..";
}
else if(answer.equals("Jeffersoncity"))
{
return "correct.....";
}
return "Sorry,but the correct ans is Jefferson City";
}
That’s going to work just great!
Moreover
That I put { on new lines doesn’t affect the outcome of your program. There are however good reasons as to why you’d want to put them on separate lines. The reason I’m writing this is because I’m highly fond of bringing up the debate all over again—making people mad.
Use .equalsIgnoreCase on Strings if not case sensitive. Also to avoid nullpointer exception use the following syntax
"Jeff City".equals(stringVar);
Related
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.
UPDATE:
Thank you all for your answers, especially pertaining to .equals().
The only detail is that the "msgCode = ..." and "msgValue = ..." statements are enough to return an empty stirngBuilder. I.e., I don't even have to declare the IF statement to make it stop working.
Any clues?
ORIGINAL:
Please let me know why StringBuilder returns nothing (perhaps doesn't even work) when I include the rest of the code (besides stringBuilder.append(...)) inside the while().
When I include just stringBuilder.append(...), then there is a return value.
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString + "\n");
// analyze the first 3 characters in the message
String msgCode = receiveString.substring(0, 3);
Number msgValue = Integer.parseInt(receiveString.substring(4, receiveString.length()-4));
// use IF-ELSE since SWITCH doesn't work with String
if (msgCode=="ATT") {
dataATT[2*dataATTcount+1] = msgValue;
dataATTcount++;
} else {
dataMED[2*dataMEDcount+1] = msgValue;
dataMEDcount++;
}
}
Thanks
use
msgCode.equals("ATT")
instead of
msgCode=="ATT"
with '==' you compare the references of the string and not the string itself.
Never-ever use == for Java string comparison. Use equals().
P.S. Okay, there might be some cases where == would be suitable. But for the vast majority of situations, equals() is the way to go.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So, for some reason I'm having problems just USING a string input.
I don't know why. Maybe it's some incredibly stupid thing everyone knows, but I don't.
Here's the non-functioning code:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
Yes, I actually do have a tutorial method somewhere else, and it works fine.
The main problem is that if I enter 'Yes' or Yes, it still goes to the final else.
I only put in the
String i = input;
and changed it from
if(input == "Yes") {
because it didn't work then, either.
So what am I doing wrong?
Don't use the == operator to compare Strings, use equals() instead, as thoroughly explained here, here, here, here or any of the numerous duplicates.
if ("Yes".equals(input))
Or even
if ("yes".equalsIgnoreCase(input))
Notice that the operation is invoked on the "yes" literal to avoid a possible NullPointerException in the case input was null and the operation was invoked on it (Yoda condition).
From the Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators:
15.21.3. Reference Equality Operators == and !=
While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
As mentioned, the problem is that you are comparing this String using the == comparator, not the .equals() method.
If you are running on Java 7, my advice, for a cleaner solution, would be also to wrap this in a switch statement:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
So, I have a question regarding the testing operators and strings. I'm trying to write a program that will take in user input of either "boy" or "girl". When the user inputs "boy", the output should be "You are a boy." When the user inputs "girl", the output should be "You are a girl."
However, when I compile and run the program, no matter what I input, the output is always "You are a girl."
Is this because the strings have no actual value like integers and therefore, testing operators cannot be used to compare them?
Also, is there anything like the assert function from python in java?
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
if (text == "boy"){
System.out.println("You are a boy.");
}
else{
System.out.println("You are a girl.");
}
}
}
Thanks a lot~
Use
text.equals("boy")
instead of
if (text == "boy")
The reason is, In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal.
But the better option is to use equalsIgnoreCase, the reason is that user may enter boy or BOY or Boy or any other combination. equalsIgnoreCase method just ignores the case and compares two strings.
text.equalsIgnoreCase("boy")
Side note. Input other than Boy will get you to print Girl. Put one more extra if condition. Also before going for comparision, being on safer side trim the string for blank spaces.
Use
text.equals("boy")
or
text.equalIgnoreCase("boy")
if its not case sensitive.
instead of
if (text == "boy")
Your coade will be something like this
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.println("Are you a boy or a girl?");
Scanner lalala = new Scanner(System.in);
String text = lalala.nextLine();
text = text.trim();
if (text.equalIgnoreCase("Boy")){
System.out.println("You are a boy.");
}
else if(text.equalIgnoreCase("Girl")){
System.out.println("You are a girl.");
} else {
System.out.println("Invalid Gender");
}
}
}
use text.equalsIgnoreCase("boy")
if you think about case also it will check content of string is same.
== is used to check for object equality.
text.equals("boy") is ok if you not consider about case.
Please use equals method for string like : if (text.equals("boy")){
== is not for string contents equality check in java
== tests if object identity is the same. When you have two string objects containing the same value this object identity won't be equal. Use the equals function to test for logical equivalence.
Your if else is wrong. Use only if here. Otherwise,
If I entered "some text", the output will be "You are a girl"
Like this
if (text.equalsIgnoreCase("boy")) {
System.out.println("You are a boy.");
}
else if (text.equalsIgnoreCase("girl")) {
System.out.println("You are a girl.");
} else {
System.out.println("You are neither a boy nor a girl");
}
It would be best to use the .equals method instead of == boy
For your other question regarding assert:
Java has an assert function. This is the sample code.
assert(x <= 50): "Not Accepted";
This code checks if integer x is greater than 50. You will see the output at the console.
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.