0

I have here my code and I am trying to check whether the user inputs Y or N to get to the switch statement, however even if I write Y or N it gives me the error message, what am I doing wrong? thanks in advance

public void anotherAction() throws IOException{
    System.out.println();
    System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
    while(!reader.hasNextLine()){
        System.out.println("Enter either 'Y' or 'N'");
    }
    String response =reader.nextLine().toUpperCase();
    while(response != "Y" || response != "N"){
        System.out.println("Enter 'Y' or 'N'");
        response = reader.nextLine();
        continue;
    }
    switch(response){
        case "Y":
            cc.getCommand(this.makeOption());
            break;
        case "N":
            System.out.println("Exiting System...");
            break;
    }
}
Andrey Arias
  • 57
  • 1
  • 10

2 Answers2

0

You should use equals() to compare Strings.

Marcelo
  • 9,916
  • 3
  • 43
  • 52
0

The above answer is correct - but you might want to minimize the amount of string comparison your doing with your primary functions (It quickly becomes hard to maintain, and you have a perfect opportunity to encapsulate user input as a bool)

Something like this may help you in the long run

    public void anotherAction() throws IOException
    {
        System.out.println();
        System.out.println("Would you like to perform an additional action? 'Y' or 'N'");
        if (getAction()) 
        {
            cc.getCommand(this.makeOption());
        }
        else {
            System.out.println("Exiting System...");
        }
    }

    private bool getAction()
    {
        while(true)
        {
            System.out.println("Enter either 'Y' or 'N'");
            String response =reader.nextLine().toUpperCase();
            if (response.equals("Y")) {
                return true;
            }
            else if (response.Equals("N")) {
                return false;
            }
            else {
                System.out.println("Wrong input, please try again...");
            }
        }
    }
  • I think I did it way to complicated by looking at your code, however I have not had good experiences when validating input with IF statements – Andrey Arias May 12 '13 at 03:15