1

My if-then-else statement is always outputting the else outcome

import java.util.Scanner;


public class NiallScanner {

public static void main(String[] args) 
{
    System.out.println("Hello, What is your name?");
    Scanner scanner = new Scanner(System.in);
    String yourName = scanner.nextLine();
    System.out.println("Is your name: "+yourName + "?");

    Scanner scanner1 = new Scanner(System.in);
    String isCorrect = scanner1.nextLine();

    if (isCorrect ==  "Yes")
    {
        System.out.println("Thank you for your confirmation!");
    }
    else
    {
        System.out.println("Retry please.");

    }

}

Any ideas why guys? I'm really new to java btw, so I may be overlooking basic coding errors.

Chandrayya G K
  • 8,719
  • 5
  • 40
  • 68
  • 8
    Read [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – PakkuDon Feb 19 '14 at 00:33

3 Answers3

2

Use "Yes".equals(isCorrect);, == compares object references, not content. Two different Strings can have the same content.

Alternatively you can use String.intern() to obtain unique references from the pool of strings; those can be safely compared using the == operator:

"Yes" == isCorrect.intern();

While both methods work, I would advice you to go with the first one. Use equals to compare objects and == to compare primitives.

Check out the Working example.

Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
1

Use equals() method instead, because == compare object reference the bit it contain to see if two object are refering to the same object. But equals() method compare the value instead. so in this case you should do: "Yes".equals(isCorrect)

If you want to check if two object are refering to the same object for example:

Object1 x = new Object1();
Object2 y = x;

if(x == y) {
//This will return true because 'y' is refering to object 'x' so both has the bit to  access the object on memory.
}

But if you want to check by value for example:

String hola1 = "hola";
String hola2 = "hola";
if(hola1.equals(hola2)){
 //Return true because both has the same value.
}
Luis Pena
  • 4,132
  • 2
  • 15
  • 23
0

Use equals method to Compare strings.== will compare the references not the content.Please find the corrected program.

public class NiallScanner {

public static void main(String[] args) {
    System.out.println("Hello, What is your name?");
    Scanner scanner = new Scanner(System.in);
    String yourName = scanner.nextLine();
    System.out.println("Is your name: "+yourName + "?");

    Scanner scanner1 = new Scanner(System.in);
    String isCorrect = scanner1.nextLine();


    if (isCorrect.equals("Yes"))
    {
        System.out.println("Thank you for your confirmation!");
    }
    else
    {

        System.out.println("Retry please.");

    }
}

}
Gundamaiah
  • 780
  • 2
  • 6
  • 30