0

I am coding a little election Program for the upcoming Election's in Germany. Well, it is not working.

public static void main(String[] args)
{
    String _Kandidat1;
    String _Kandidat2;

    _Kandidat1 = JOptionPane.showInputDialog("Do you Vote for the AFD or for the CDU ?");
    if (_Kandidat1 == "AFD")
        System.out.println("The AFD won the election!");
    else
        System.out.println("The CDU won the election!");
    }
}

If I type in "AFD" it says the CDU won. If I type in "CDU" in nothing happens. I'm not sure, but I think the mistake is in if (_Kandidat1 == "AFD")

Any solutions?

Davis Broda
  • 4,102
  • 5
  • 23
  • 37

2 Answers2

4

You need to use equals, otherwise you compare the reference:

_Kandidat1.equals("AFD")
ronhash
  • 854
  • 7
  • 16
0

You should read documentation of java for String class first. This class is not a primitive type hence equality should not be checked with ==. You should check the string equality with .equals() method.

if (_Kandidat1.equals("AFD"))
    System.out.println("The AFD won the election!");
else
    System.out.println("The CDU won the election!");
}
kk.
  • 3,747
  • 12
  • 36
  • 67