Simple Java If/Else if Statement Unfunctional [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I was working on my game I am making, when I came across an error. My if/else if statement skips right to the else if statement, even if it shouldn't.
String neededCredits = "200";
if(Peeamnt.getText() == neededCredits) {
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(Peeamnt.getText() == neededCredits))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}
Even if the text of Peeamnt is an even 200, the code will jump to the else if statement, telling me that I don't have 200 Pee Credits. (The game I am making included a lot of toilet humor.) Anyway, if anyone sees the error I have in this code, please let me know. Let me know if you need more code.

With a Java String object, the == operator doesn't compare the string value.
Try changing the first if comparison to:
if(Peeamnt.getText().equals(neededCredits)) {
You will need to do something similar for the else if as well.

Strings are objects. Objects have a reference. Two String objects containing the same sequence of characters may not be the same object, thus having different references. The == operator (generally) checks for reference equality.
To compare the character sequence of two String objects for equality, you have the equals method. So use Peeamnt.getText().equals(neededCredits) instead.

String is an Object. Comparing Object, you have to use equals to judge whether the Object content is same. Using == is to compare Object reference

Use equals method to compare String object, because == operator means you compare object base on memory address. Always remember to never use == to compare objects in Java.

Try to use equals method if the getText() returns a string don 't use == sign. I suppose that getText() returns aString` object.
FYI: Double equal sign is used to see if two Objects are the same
and TO check if the objects has the same value equals() method should be used. Note: The objects that You compare with equals() should override it otherwise the results are corrupted, and the last thing when You overridesequals() method remember to override hashCode() too.

Use method equals to compare String object, because == operator means you compare object base on memory address.
* never use == to compare object.
String neededCredits = "200";
if(neededCredits.equals(Peeamnt.getText()) {//compare following you never see, because nullPointerException "neededCredits" always has value :-)
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(neededCredits.equals(Peeamnt.getText()))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}

Related

Equal ArrayLists (Java)

.containsAll will work but .equals is not working.
You are adding the numbers everytime. You should use local variables or local initialization. Else your passcode list gets 5 more numbers everytime you call your function.
Because you said "a security keypad", I have to say ignore what anyone else says that is technically correct, you are doing it wrong. By storing the passcode in a "plain" format, you might as well just leave a sticky note on the keypad with the passcode on it.
What you should be doing is hashing the input and the passcode and comparing the hashed versions. And don't use hashCode(), that function is unreliable for this purpose. (Example of how to hash)
Also, according to the Java Docs, equals is the correct way to check. You are miss-handling your list instances. You should step through the debugger to see everywhere in your code that you do something that alters your global variables.
I think you have a problem where you are comparing your arrays. Have a look at this SO question: equals vs Arrays.equals in Java
if (digitList.size() == 5 && digitList.equals(passcode)) { // are the arrays the same array?
guideArea.setText("Correct Password.");
digitList.clear();
}
what it should be:
if (digitList.size() == 5 && Arrays.equals(digitList, passcode)) { // are the two arrays CONTENT the same
guideArea.setText("Correct Password.");
digitList.clear();
}

String equality using replace and substring methods

I have some questions about string comparison.I couln't find any answers concerning replace and substring methods in particular.So here is the code
public static void main(String args[]) {
if ("hello".substring(0) == "hello")
System.out.println("statement 1 is true");
if ("hello".substring(1) == "ello")
System.out.println("statement 2 is true");
if ("hello".replace('l', 'l') == "hello")
System.out.println("statement 3 is true");
if ("hello".replace('h', 'H') == "Hello")
System.out.println("statement 4 is true");
if ("hello".replace('h', 'H') == "hello".replace('h', 'H'))
System.out.println("statement 5 is true");
}
The output is:
statement 1 is true
statement 3 is true
Does the substring method create a new String().If so why is statement one true,yet 2 is not?Same question goes about statement 3 and 4.Thank you.
I assume you are aware of how string comparison works. So i'll try to explain what is happening.
Strings in java are immutable objects, so once created you can't change them.
To reduce overhead in creating the "same" string object over and over again, there is a pool of already used/created strings.
Now when you now compare if two string objects are the same it compares whether the objects themselves are the same. if you do "hello".substr(0) it will "create" a string object with "hello" in it. Since "hello" was already used, the string object containing "hello" is already in the string object pool. And if you now again "create" the string object "hello" to compare with, it will return the same object from the pool.
The same is happening with the "hello".replace("l","l") it will return the same "hello" string object like above.
But you can not rely on that, because the string-pool can get emptied at any time.
Further reading for "internalling strings" http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#intern()
BUT, if your question is about how to compare string themselves not the objects containing you strings, you should really use "hello".equals("hello") because then it will compare the real content. (As mentioned above)
If you compare strings with .equals() (to test value equality) rather than == (which tests referential equality), your program will output different results.
You should not be comparing strings like that in java. == is comparing the string references instead of the strings itself. Use .equals() method already defined for quality comparison of strings.
str1.equals("Hello");
The substring() method (which was changed in Java 7), will always return a new object. The only exception to this is if it is to return the whole string (substring(0)). Then, it will return it from the pool and the equality expression (==) will evaluate to true. This is the reason why statement 1 is true, but statement 2 false.
An example.

if switch not working

I am trying to make a control that will block the user from entering a term year for their home loan that is over 30.
HomeLoan hLoan=new HomeLoan(name, custID, loanID);
System.out.println("You selected Home Loan");
System.out.println("Enter term: ");
term=input.nextInt();
boolean l=false;
boolean s = hLoan.termCorrect(term);
System.out.println(s);
if (s=true){
System.out.println("Error: Maximum of 30 years");}
else {l=false;}
It calls a method that termCorrect() that determines if the term is over 30, and returns true or false. When I run it, the value of s is correct for the input that I use, but it always run the error message for some reason, regardless of s.
Any help would be greatly appreciated.
You are using the assignment operator =:
if (s=true){
Use the comparison operator == instead:
if (s == true) {
or, because it's already a boolean, use s itself:
if (s)
The last form is preferable. It's concise, and there's no chance to an operator confused with =.
Assignment operator in if statement is invalid. Change from
if (s=true){// this invalid
To
if (s){
= is assignment. == is equality comparison.
Your if statement is incorrect. By using s=true you are setting s to true inside the if. The equality operator in Java is ==. Therefore, you could do this:
if(s==true)
Or, since s==true is logically equivalent to s (think about it), you can do this:
if(s)

Why is not "Ellie" == "Ellie", when one of them was read from the user? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
The following question is from a quiz I took a few weeks ago and got incorrect, but the answer wasn't provided:
Consider the following code, which contains no compile errors:
String secret = "Ellie";
Scanner kb = new Scanner(System.in);
System.out.println("Guess which name I'm thinking of:");
String guess = kb.next();
if (guess == secret)
{
System.out.println("Wow! You're smart!");
}
else
{
System.out.println("Wrong!");
System.out.println("You guessed: " + guess);
System.out.println("The correct answer was: " + secret);
}
Suppose the user enters "Ellie" at the prompt.
What output would result, and why that output and not the other output?
Here was my incorrect answer:
The output would be the else statement "WRONG!" because of the capitalization of the letter 'E'. A solution to this would be
to either change the String secret to "ellie" as well as the user's guess, or one can write in the ignoreCase keyword to
String secret.
The program actually outputs "Wrong", I tested it.
Aside from simply knowing the answer, could someone really explain this to me so I can understand the concept better?
The == does a reference comparison, and so it'll always say 'Wrong!', even if the two string references are equal. In order for it to match correctly, it would have to use secret.equals( guess ).
In java:
the == operator tests if the two objects are the same exact instance
the .equals() method of String compares if the objects "have the same value"
Since the user input the value, it's a new instance of String, so it will never be true that secret == input.
You should always use str1.equals(str2) when comparing Strings.

Strings don't seem to be equal in Java on Android, even though they print the same

I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }

Categories

Resources