Hello I have made a simple program, but I have a problem with my IF...ELSE statement. Il explain under the code.

Main Class:

public class Learnt {
    //Main void in Learnt class
    public static void main(String args[]){

        //Ask's user for name then prints it
        String AskForUsersName = "What is your name?\nName - ";

        //Uses NotMain.java
        NotMain ScanForName = new NotMain();

        //Ask's user how they are
        System.out.print("How are you feeling today? (Good / Bad)\nYou are feeling - ");

        //Use's HowIsUser.java
        HowIsUser UserIs = new HowIsUser();



Second class(Working):

import java.util.Scanner;

public class NotMain {
    // Defines GetUserInput in class NotMain
    public void GetUserInput(){

        //Scan's for user's name
        Scanner Scan = new Scanner(System.in);
        String UserName = Scan.nextLine();

        //Creates a variable FullSentance then print's it
        String FullSentance = ("Nice to meet you " + UserName);



Third Class(Not working):

import java.util.Scanner;

public class HowIsUser {
    // defines GetUserInput in class HowIsUser
    public void GetUserInput(){

        //Scan's for user input
        Scanner Scan = new Scanner(System.in);
        String HowIsUser = Scan.nextLine();

        // Determin's what to say if user is good / bad
        if(HowIsUser == "Good" || HowIsUser == "good"){
            System.out.println("Thats good! :)");

        }else if(HowIsUser == "Bad" || HowIsUser == "bad"){
            System.out.println("Sorry too hear :(");

            System.out.println("Invalid input");


The if and the else statement doesn't come up with any error's. But it says Invalid input when I enter Good or good or Bad or bad. Why is it doing this? Thanks.

because you are comparing Strings using the == comparator, while you should use the equals method, like this:

if ( HowIsUser.equals("GOOD") || HowIsUser.equals("good"))

especially for the String class, there is an easier way to write this:

if ( HowIsUser.equalsIgnoreCase("good"))

which will return true for both "GOOD" and "good", just as it will for "GoOd" or any other way to spell good with different upper/lowercase combo's.

you may also want to try and follow the naming conventions that are used in Java.

for the classname, HowIsUser is well written, but when declaring a variable, you should start it with a lowercase:

String howIsUser = ...

would be better.

commented: Useful +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.