0

I am not sure what exactly is wrong with my code. I am just testing out the logic for an 'if' 'else if' 'else' code block. I ran the program and each time I typed in one of the 3 fruits mentioned in the prompt, all I get is the print statement from the else block. I did a debug and the code is not even stepping into the curly braces meant for the if block of the respective fruit. Hope someone can tell me what is wrong with my code. Thank you.

import java.util.Scanner;


public class IfDriver {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s=null;
        System.out.println("Please enter the fruit: ");
        String fruit = sc.next();
        if(fruit=="apple"){
            System.out.println("It is an apple");
        }
        else if(fruit=="orange"){
            System.out.println("It is an orange");
        }
        else if(fruit=="pear"){
            System.out.println("It is a pear");
        }
        else {
            System.out.println("No such fruit");
        }
    }
}
javaperson
  • 109
  • 1
  • 12
  • 1
    You are testing whether `fruit` is the same object as `"apple"`, which means you are testing for identity. They would be at the same place in memory and have the same reference. Instead you should test for equality using the `equals` method: `if (fruit.equals("apple")) {}`. – Raimund Krämer Dec 08 '15 at 11:00
  • Thanks Eran and D.Everhard – javaperson Dec 09 '15 at 02:48

0 Answers0