Comparing String with String Values [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java String.equals versus ==
I have a string called DomainType which usually holds values like "edu,com,org..etc" from a url. I used an if else statement to help check the data type and output a JOptionPane. For some reason whenever you type any domain type, It gives you the last option.
Here is a Snippet from the code I wrote:
DomainType = URL.substring(URLlength - 3, URLlength);
if (DomainType == "gov") {
JOptionPane.showMessageDialog(null, "This is a Government web address.");
}
else if (DomainType == "edu") {
JOptionPane.showMessageDialog(null, "This is a University web address.");
}
else if (DomainType == "com") {
JOptionPane.showMessageDialog(null, "This is a Business web address.");
}
else if (DomainType == "org") {
JOptionPane.showMessageDialog(null, "This is a Organization web address");
}
else {
JOptionPane.showMessageDialog(null, "This is an unknown web address type.");
}
so the DomainType gives me edu or com no problem but i think it's my if statement I'm not doing right.

When comparing strings, never use ==, use equals. So, instead of
DomainType == "org"
use
DomainType.equals("org")
Why? == will compare references. That means: memory values. And they may not be equal for your strings. equals will compare values, and that is what you want.

To compare content use equals, not == (which compares references):
if (DomainType.equals("gov")) {

On a side note, a mega-if is probably not the most elegant way to do that - http://www.antiifcampaign.com/ - sorry, just being pedantic.
The .equals() method is the right way to compare objects indeed.

Related

Comparing two strings doesn’t work [duplicate]

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);

Problems with String Input [duplicate]

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'");
}

Java Check If Two JTextField Has The Same Content [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have two JTextFields txf1 and txf2.
In both of them I input the same content (for example: "test").
I made and If statement:
if (txf1.getText() == txf2.getText()) {
System.out.println("Equal");
} else {
System.out.println("Error");
}
Why it prints out the error message? I even made a System.out.println(txf1.getText()) and System.out.println(txf2.getText()) and the same looks equal, but prints out the error message?
String comparison in Java is done using String#equals, using == means you are comparing the memory reference of the objects, which won't always return true when you think it should.
Try something more like....
if (txf1.getText().equals(txf2.getText())) {
...instead
Also you can use this good practice which makes your text box entries efficient.
if (txf1.getText().trim().equals(txf2.getText().trim())) {
Use the equals method to compare Strings. == only compares the object reference. equals compares the actual content of the Strings.
Your code should be something like this:
if (txf1.getText().equals(txf2.getText())) {
System.out.println("Equal");
} else {
System.out.println("Error");
}

Beginner Java strings [duplicate]

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.

Can't break the while loop [duplicate]

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.

Categories

Resources