Java 无法使用JOptionPane在showConfirmDialog中将int转换为字符串
我试图在主Java类中运行以下代码:Java 无法使用JOptionPane在showConfirmDialog中将int转换为字符串,java,joptionpane,Java,Joptionpane,我试图在主Java类中运行以下代码: personName = JOptionPane.showInputDialog("Enter the name of the person !"); onepty.setNameOfPerson(personName); SpeechDecision = JOptionPane.showConfirmDialog(null, "Sele
personName = JOptionPane.showInputDialog("Enter the name of the person !");
onepty.setNameOfPerson(personName);
SpeechDecision = JOptionPane.showConfirmDialog(null,
"Select Yes or No", "choose one", JOptionPane.YES_NO_OPTION);
onepty.speechCheck(speechDecision);
下面的方法是在我通过onepty
对象访问的数据定义类中定义的,如上所示:
public String speechCheck(String str){
if(str == "Yes" || str =="YES"||str == "Y" ||str== "y"||str=="YEs"||str=="yeS"||str=="yES"){
this.speechVar = str;
}
else {
this.speechVar = str;
}
}
但是在使用jGrasp编译之后,我得到了以下错误:
error: incompatible types: int cannot be converted to String
speechDecision = JOptionPane.showConfirmDialog(null,
^
1 error
虽然错误是不言自明的,但由于我是net to jOptionPane,我想知道用户在单击“是”或“否”选项后选择的按钮输入是否存储为整数而不是字符串?我是否需要修改我的
speechCheck
方法以捕获整数值?请告知。变量SpeechDecision
可能是字符串,它应该是int
,因为这是从中返回的值,请参见其签名:
public static int showConfirmDialog(...)
↑
几点注意:
- 遵循
- 不要使用
来比较字符串,而是使用=
equals
- 缩进您的代码以实现更美好的世界
- 您可以这样做:
int speechDecision = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION)
{
// Do something here
}
您必须使用JOptionPane默认常量 JOptionPane.YES\u是和的选项 JOptionPane.NO\u选项用于 演讲决策的类型应该是整数 所以,代码看起来像
int speechDecision = JOptionPane.showConfirmDialog(null, "Select Yes No", "choose one", JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION){
// Do something here for yes
}
else{
// Do something here for no
}
说真的,你现在用==来比较字符串
showConfirmDialog
return typeint
notString
。没有显示speechDecision
的声明是没有帮助的。是的,showConfirmDialog
方法返回int
,您可以很容易地通过文档进行验证。顺便说一句,不要像那样比较字符串。请参见是,speechDecision
是一个字符串变量。由于返回类型是int
,因此我的speechCheck
方法没有任何用处。我相信现在的单词是“equalsIgnoreCase”,它会将代码减少到现在的一半。检查所需的参数以及传递的内容。您能告诉我选择“是”或“否”时返回的整数值是多少吗?@John请查看链接文档。我在文档返回中看到了以下内容:一个表示用户所选选项的int。但是,我仍然不确定当用户选择“是”或“否”时将返回什么整数值。基于此,我正在考虑修改我的方法。@John它是JOptionPane.Yes\u选项
或JOptionPane.No\u选项
我尝试使用以下命令打印该值:JOptionPane.showMessageDialog(null,“语音检查”+speechDecision,“这是标题”,JOptionPane.INFORMATION_MESSAGE)
我看到如果选择“否”,我会得到0
和1
。