This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
Well, I really tried to solve (and google) it, but I couldn't.
And sorry for my english and for that idiotic title (This one is the best that came to mind) :)
System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s == "yes"){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
console:
AM I A GENIUS?
yes
I am not a genius(
if (s == "yes") --->> NEVER
instead use
if (s.equals("yes"))
EDIT: just for explain: the first statement is a boolean operator that controls if the references of the object s and the object "yes" are the same.
the second one compares the real content of the String variable.
So, in general, you should never use boolean comparison when using not primitive types.
In fact, you are comparing references and not the 2 String objects.
What you should do is the following:
System.out.println("AM I A GENIUS?");
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.equals("yes")){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
The equals method of the class String now compares the Strings s and "yes" characterwise.
I think Roman was right, you should be using .equalsnot ==, they imply different things.
== checks the references to the objects, which can work depending on what what you're comparing, but it's best to use .equals() which compares the content of the strings.
Your code should look like this:
String s = scan.nextLine();
if (s.quals("yes")){
System.out.println("^_^");
}
else{
System.out.println("I am not a genius(");
}
I'd also recommend using a .toLowerCase() on the user input, because that also cause the conditional to return false when the user types "Yes" as supposed to "yes". That would look like: s=s.toLowerCase();
Hope this helps.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to write a simple hangman game in java for my college class. For some reason the if statement never returns seems to think that the two substrings being compared are equal. The two print statements show that by all rights the two should equate.
public String guessLetter(String letter)
{
String blanks = "";
String theWord="FOO";
for(int i=0; i<=theWord.length()-1; i++)
{
System.out.print(letter.substring(0,1).toUpperCase());
System.out.print(theWord.substring(i,i+1)+ "\n");
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1)))
{
blanks = blanks + theWord.substring(i,i+1);
}
else
{
blanks = blanks + "___ ";
}
}
return blanks;
}
EDIT - As a great many people have pointed out, when comparing Strings, one must use the equals method instead of ==. I was unaware.
You are comparing a String so use "String".equals() dont use ==
use like this:
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
Java dont have == for string
you must use string1.equals(string2) function
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1))) \ this is wrong for strings
When you compare strings you should use .equals or .equalsIgnorecase
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
ans also checkout the difference between == and .equals in java good explanation is given there.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
When I debug this code I noticed that the If statement does not ever switch the boolean type sales variable to true... This is bugging me because I know that answer = "y" when it gets to the If statement. Help please! and yes I did import java.util.Scanner
Scanner input = new Scanner(System.in);
boolean sales = false;
String answer;
System.out.print("Will you be calculating the Sales department pay aswell? (y or n):");
answer = input.nextLine().trim();
if (answer == "y")
{
sales = true;
}
i have
The correct way to compare strings is:
if (answer.equals("y"))
Notice that in Java equals() is used for testing equality between objects, whereas the == operator is used for testing identity. They're two different concepts, and most of the time you're interested in equality.
As the #MadProgrammer suggests, inverting the comparison order is a good idea - it'll be safer in case answer is null:
if ("y".equals(answer))
You should use equals() to compare strings:
if (answer.equals("y")) {
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to implement the System.exit(0); in java to terminate my program when the word "exit" is typed into the console. I wrote the following method:
public static void exit(){
Scanner input = new Scanner(System.in);
Str1 = input.next(String);
if (str1 = "exit"){
System.exit(0);
}
else if (str1 = "clear"){
System.out.println("0.0");
}
}
and it doesn't seem to be working. Does anyone have any suggestions?
Thanks
P.S the "clear" is just supposed to return 0.0 when "clear" is entered into the console, if you could not already tell.
Compare strings with equals() not with ==.
The reason is that == just compares object references/primitives,where as String's .equals() method checks equality.
if (str1.equals("exit")){
}
and also
else if (str1.equals("clear")){
}
Might useful :What are the benefits of "String".equals(otherString)
if(str.equals("exit"))
or
if(str.equalsIgnoreCase("exit"))
or
if(str == "exit")
instead of
if (str1 = "exit"){
With if (str1 = "exit") you use an allocation instead of a compare.
You can compare with the equals() method.
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. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
So use:
if ("exit".equals(str1)){
}
Besides equals(), the input.next(String pattern); require pattern not String data type
Change your code to:
public static void exit(){
Scanner input = new Scanner(System.in);
str1 = input.next(); //assumed str1 is global variable
if (str1.equals("exit")){
System.exit(0);
}
else if (str1.equals("clear")){
System.out.println("0.0");
}
}
Notes : http://www.tutorialspoint.com/java/util/scanner_next_string.htm
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
(Sorry for the weird title, but I can't figure out what actually the problem is)
The following code should get a String from the command line first (which works), then the input is being splitted (works perfectly, too; I checked by printing both Strings before the if/else as you can see in the part I commented out again) and then it should check what the first part of the splitted String is. And for example if it equals "tweet" it should procedure with the Tweet method.
But somehow it doesn't get that right. It always executes the else statement...
Scanner sc = new Scanner(System.in);
System.out.print("> ");
String input = sc.nextLine();
String[] splitString = input.split(" ");
if(splitString.length != 2){ throw new IllegalArgumentException(); }
String command = splitString[0];
String value = splitString[1];
/*System.out.print(command);
System.out.print(value);*/
if(command == "tweet") { Tweet(value); }
else if(command == "help") { ShowHelp(); }
else { System.out.println("Command "+command+" not found."); }
I tried entering "tweet asdf", but it returns
> tweet asdf
Command tweet not found.
What did I do wrong? I'm confused D:
Use the .equals method instead of ==.
== compares the references. .equals will compare the actual content of the two strings.
When comparing strings, you will almost always want to use .equals not == as usually you are wanting to compare content, not reference.
You're using == to compare two objects. This compares their references. Use if(command.equals("tweet")) instead to compare by values.
Due to string interning depending on the JVM and implementation(official classpath, GNU classpath, etc) your approach may operate properly hit-or-miss.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String is not equal to string?
I'm new to java and I can't figure out what's wrong with this code block.
I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.
Scanner input = new Scanner(System.in);
System.out.println("Enter ID :");
String employeeId = input.nextLine();
int index = -1;
for(int i = 0 ; i < employeeCounter ; i++)
{
if(employeeId == employeeNumber[i])
{
index = i;
}
}
if(index == -1)
{
System.out.println("Invalid");
return;
}
I always get to the 'Invalid' part. Any idea why ?
Thanks in advance
employeeNumber[0] is "12345"
employeeId is "12345"
but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].
Don't compare strings with ==.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
As others have pointed - full code will be helpful, but my guess would be this line of the code:
if(employeeId == employeeNumber[i])
You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.
When you use == with two string, it compares pointer addresses
You should use firststring.equals(secondstring) in order to compare two strings
Use equals() method to compare Strings
if(employeeId.equals(employeeNumber[i])){}
When you compare strings, use
String1.equals(String2);
This should give you the result
"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.