带有JOptionPane的Java选举程序
我正在为即将到来的德国选举编写一个小的选举程序。嗯,它不起作用了带有JOptionPane的Java选举程序,java,joptionpane,Java,Joptionpane,我正在为即将到来的德国选举编写一个小的选举程序。嗯,它不起作用了 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") Sy
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!");
}
}
如果我输入“AFD”,它会说基民盟赢了。如果我在中键入“CDU”,则什么也不会发生。
我不确定,但我认为错误在于if(_Kandidat1==“AFD”)
有解决方案吗?您需要使用equals,否则您需要比较参考:
_Kandidat1.equals("AFD")
您需要使用equals,否则将比较引用:
_Kandidat1.equals("AFD")
您应该首先阅读
String
类的java文档。此类不是基元类型,因此不应使用==
检查相等性。您应该使用.equals()
方法检查字符串的相等性
if (_Kandidat1.equals("AFD"))
System.out.println("The AFD won the election!");
else
System.out.println("The CDU won the election!");
}
您应该首先阅读
String
类的java文档。此类不是基元类型,因此不应使用==
检查相等性。您应该使用.equals()
方法检查字符串的相等性
if (_Kandidat1.equals("AFD"))
System.out.println("The AFD won the election!");
else
System.out.println("The CDU won the election!");
}
使用.equals()
方法使用.equals()
方法