Why doesn't this code terminate my program? Java [duplicate] - java

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

Related

Why does "T" not equal "T" in this example? [duplicate]

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.

Java if statement equality [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
How can it be possible, that If statement doesn't understand two equal things that they are the same?
Situation:
I write into txfName field only letter b and then push button "Ok".
Code:
String letter = "b";
boolean same = false;
if (letter == txfName.getText()) {
same == true;
}
After if statement program shows me that variable same is false. Why? How can it be possible?
If I write code like this:
String letter = "b";
boolean same = false;
if (letter == "b") {
same == true;
}
Then after if statement program shows me that variable same is true. I don't understand, how it can be possible.
== compares to see if two objects are the same. When you are dealing with strings they are objects, so they may not have the same reference event though they can have the same value. You want to use .equals() instead.
For more details, Strings are special in java, as there are some internal workings that have a String pool. So in some cases the == may actually seem to be working, but in other cases it may not be. The reason is the String pool tries to cache recently used Strings to reduce the memory overhead. Anyway .equals() is what you are looking for.
for your first question
String letter = "b";
boolean same = false;
if (letter.equals( txfName.getText())) {
same = true;
}
return same;
will return true if txfName.getText() returns "b"
To compare objects in java use .equals() method instead of "==" operator
Replace the following code
if (letter == txfName.getText())
to
if (letter.equals(txfName.getText()))

Java Scanner: That looks easy [duplicate]

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.

My program is ignoring my if statement and goes straight to the else [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
String firstanswer = scan.nextLine();
if(firstanswer == answer2)
{
System.out.println("OK lets get started");
}
else
{
System.out.println("That is incorrect, of course you want to play");
}
//answer2 is set to "yes", i declared it above
make it firstanswer.equals(answer2) instead of firstanswer == answer2.
When you want to check for equality of String in java then use equals method instead of == operator.
equals method checks whether the contents of String objects are same
== operator checks whether both the reference variables refer to same String object
To understand about strings and equality, read String comparison with equals and assignment operator It will help you understand the concept well.
Use equals() instead of == to compare strings.
if(firstanswer.equals(answer2)) is what you're looking for.
firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.

Why don't strings compare as equal? [duplicate]

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.

Categories