Crislips Crislips - 6 months ago 15
Java Question

Why won't my if loop recognize the string the user defines?

I'm writing a super simply program just to teach myself about Java. I've tried so hard to find the answer for this before asking a question, but as far as I know, this just doesn't make sense.

This specific issue that I'm having is in the main method. When it asks the user to input 'Yes' or 'No,' no matter what is entered, it just skips to the else option. No if, no else if. I even included at the bottom to print the string "User" to see if that was there error, and it prints no problem. So that makes me think the error is with the formatting of the if loop. But as far as I've seen, in every thread I've looked at, there is no issue. I've tried simplifying it to just "Yes" and took out all the other user error options, and there is still not luck. It just skips to the else.

What am I doing wrong. It's unbelievable to me that I can't figure this out.

import java.util.*;

public class Droid {

int batteryLevel;
String User;

public Droid() {
batteryLevel = 100;
}

public void activate() {
System.out.println("Activated. How can I help you?");
batteryLevel = batteryLevel - 5;
System.out.println("Battery level is: " + batteryLevel + " percent.");
}

public void chargeBattery(int minutes) {
System.out.println("Droid charging...");
batteryLevel = batteryLevel + minutes;
if(batteryLevel > 100) {
batteryLevel = 100;
System.out.println("Battery level is: " + batteryLevel + " percent.");
} else {
System.out.println("Battery level is: " + batteryLevel + " percent.");
}
}

public int checkBatteryLevel() {
System.out.println("Battery level is: " + batteryLevel + " percent.");
return batteryLevel;
}

public void hover(int feet) {
if(feet > 2) {
System.out.println("Error! I cannot hover above 2 feet.");
} else {
System.out.println("Hovering...");
batteryLevel = batteryLevel - 20;
System.out.println("Battery level is: " + batteryLevel + " percent.");
}
}



public static void main(String[] args) {
Droid R2D2 = new Droid();
System.out.println("Your droid is fully charged. Would you like to use it?");
System.out.println("Type 'Yes' or 'No.' ");
Scanner reader = new Scanner(System.in); // Reading from System.in
String User = reader.nextLine();
if (User == "Yes" || User == "yes" || User == "Yes." || User == "yes.") {
R2D2.activate();
} else if ((User == "No") || (User == "no") || (User == "No.") || (User == "no.")) {
System.out.println("Have a nice day! I'll be waiting for you to come back!");

} else {
System.out.println("That is not 'Yes' or 'No,' please try again!");

}

System.out.println(User);


reader.close();
}
}

Answer

In java you can check equality in strings using .equals ()

if (myString.equals ("YES"))
{
    //do something
}

"==" compares memory address of the string because it is an object. This operator will return false since the memory address is not the same.