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,051
  • 5
  • 23
  • 36

2 Answers2

4

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

_Kandidat1.equals("AFD")
ronhash
  • 794
  • 6
  • 15
1

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,288
  • 11
  • 33
  • 60