[英]I'm trying to understand why I'm receiving "String seems to be unrelated to String[]"
我正在创建一个项目,其中某些形状的面积或体积是使用 java 中的下拉菜单计算的。我在编译时没有任何错误,但是我收到消息“不太可能是 equals() 的参数类型:String 似乎是与 String[] 无关”。 如前所述,它符合要求,但在运行时它允许选择面积/体积,但它没有到达下一个选项窗格 select 形状。
该消息出现在:if (choices.equals("Area")) 和:if (choices.equals("Volume"))
`
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String[] args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog(null, "What would you like to calculate?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices,
choices[0]);
System.out.println(question);
if (choices.equals("Area"))
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog(null, "What shape will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices2D,
choices2D[0]);
System.out.println(question2D);
}
//user chooses volume
if (choices.equals("Volume"))
{
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog(null, "What figure will you choose?",
"Shapes", JOptionPane.QUESTION_MESSAGE, null,
choices3D,
choices3D[0]);
System.out.println(question3D);
}
}
}
`
我最初将选项链接到一个开关,但会不断出错,将其更改为 if 语句后,它将编译但无法正常运行。
您的比较是choices.equals(…)
,但您的意思是比较来自保管箱的选择,并且存储在question
中。 所以比较应该是question.equals(…)
。
或者,试试这个:
import javax.swing.JOptionPane;
public class Shapes
{
public static void main(String... args)
{
//Dropdown menu for area and volume
String[] choices = {"Area", "Volume"};
String question = (String) JOptionPane.showInputDialog( null,
"What would you like to calculate?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices,
choices[0]) ;
System.out.println(question);
switch( question )
{
case "Area":
{
//user chooses area
String[] choices2D = {"triangle", "parallelogram", "rectangle", "trapezoid", "circle"};
String question2D = (String) JOptionPane.showInputDialog( null,
"What shape will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices2D,
choices2D[0] );
System.out.println( question2D );
break;
}
case "Volume":
{
//user chooses volume
String[] choices3D = {"cone", "cylinder", "rectanglular prism", "trapezoid prism", "sphere"};
String question3D = (String) JOptionPane.showInputDialog( null,
"What figure will you choose?",
"Shapes",
JOptionPane.QUESTION_MESSAGE,
null,
choices3D,
choices3D[0] );
System.out.println( question3D );
break;
}
}
}
}
您还可以使用新的switch-case
语法并通过使用enum
s 进行各种选择来进一步优化。
您正在将整个数组与单个字符串进行比较。 使用 choices[0].equals("Area")。 现在,这会将选择数组与索引 0 处的字符串与区域进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.