-1

I'm trying to figure out why my function isn't working as it should. The code is fairly basic and self explanatory. Here is the function:

public static void Greet(){
    System.out.println("Hello, what is your name? ");
    name = scan.nextLine();
    do{
        System.out.println("Would you like to order some coffee, " + name + "? (y/n) ");
        input = scan.nextLine();
        if(input == "y"){
            System.out.println("Great! Let's get started.");
            break;
        }
        else if(input == "n"){
            System.out.println("Come back next time, " + name + ".");
            System.exit(0);
        }
        else{
            System.out.println("Invalid response. Try again.");
        }
    }
    while(true);
}

Basically, regardless of what I enter as "input" on line 5, the function will treat it as if I hadn't entered a 'y' or 'n', it just constantly loops the while(true) and printing "Invalid response. Try again." I have no idea why my if/else statements aren't working correctly. Any help would be appreciated, thanks!

Jasper Squire
  • 45
  • 1
  • 4
  • `break` will break you out of the loop – MadProgrammer Apr 24 '15 at 05:19
  • change `input == "y"` to `"y".equals(input)` – Ambrish Apr 24 '15 at 05:19
  • I have a break on line 9, but that isn't the problem. The problem is regardless of what I input, it consistently loops to the final 'else' statement. – Jasper Squire Apr 24 '15 at 05:20
  • I replaced `input == "y"` and `input == "n"` with `"y".equalsIgnoreCase(input)` and `"n".equalsIgnoreCase(input)` and it seems to work fine for me – MadProgrammer Apr 24 '15 at 05:27
  • @MadProgrammer my bad - please ignore – Nir Alfasi Apr 24 '15 at 05:28
  • @JasperSquire Before asking questions first you need to read Java fundamental basics and learn how to compare string or char and what is difference between "==" and equals() method. – Ranjeet Apr 24 '15 at 05:36
  • Thanks guys, yeah it works when I replace 'input == "y"' with '(input.trim()).equals("y"))' Wow it's amazing how the smallest errors can make me sit for hours on end trying to find a solution. StackOverflow you are my hero – Jasper Squire Apr 24 '15 at 05:36
  • @Ranjeet In my classes, we haven't learnt the equals() method, we're still using "==" so that's why I relied on it. I've learnt from my mistake though, thank you. – Jasper Squire Apr 24 '15 at 05:38

2 Answers2

0

Compare String by equals not by ==

if((input.trim()).equals("y")){

equals compares the value
== comapres the reference

singhakash
  • 7,891
  • 6
  • 31
  • 65
0

Compare with equals.

if(input.equals("y")){
            System.out.println("Great! Let's get started.");
            break;
        }
        else if(input.equals("n")){
            System.out.println("Come back next time, " + name + ".");
            System.exit(0);
        }
DSF
  • 804
  • 7
  • 15