1

For the following code, if I type y on the keyboard, it enters the else portion of the branch statement. Why is that?

    public static void getInput(){
   String response; 
    String[] coins = new String[6]; 

    System.out.println("Would you like to enter your own amount? (y/n)");  

    Scanner sc = new Scanner(System.in);
    response=sc.nextLine();

    if (response=="y"){
       System.out.println("You entered y");
        }
   else{
       System.out.println("You did not enter y, you entered " + response);
        }
    }
1
  • you don't have a main class in this program... Commented Dec 26, 2011 at 4:49

2 Answers 2

3

You want response.equals("y").

Sign up to request clarification or add additional context in comments.

1 Comment

It's an easy mistake to make.
1

Problem is in condition if(response=="y").

the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

Use

(response.equals("y")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.