0

I am new to Java and I thought I'd do some practice on my own with Scanners and Boolean. My problem is that when I run the code below, the program doesn't output anything that is within the if or else statements.

My question is: how to I make the code print out the output within the if and else statements?

The code is:

import java.util.Scanner;
public class ScannerPractice
{
    public static void main(String[] args)
    {
        System.out.println("\tHello!");
        System.out.println("\tPlease enter you're name.");

        Scanner input= new Scanner(System.in);
        String name;
        name= input.next();

        System.out.println("\tYour name is " + name + "?"  );

        String yn;
        yn= input.next();

        if (yn=="yes") 
        {
            System.out.println("\tThats a good name");
        }
        else if (yn=="no")
        {
            System.out.println("\tWhy did you lie to me?");
            input.next();
            System.out.println("\tI don't think I can forgive you\n\tGoodbye forever!");
        }
    }
}

Thank you in advance.

2 Answers2

3

You are evaluating strings with the primitive equality operator == rather than the Object equality operator .equals()

andrewdleach
  • 2,458
  • 2
  • 17
  • 25
1

You don't want to use ==. Instead use .equals() for your comparison. == compares the references themselves.

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37