1

下面是我的代码 Stud is player 但 if (Stud.equals("North")) 说它无法比较是否有另一种方法来比较它们?

String[] options = new String[] {"North", "South", "East", "West"}; 

JOptionPane.showOptionDialog(null, p + " " + Stud.distance(Comp) + " away" +  
    " Which way do you want to move?", "" + p + " is at " + Stud.getX() + ", " + Stud.getY() ,  
    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
    null, options, options[0]);

if (options.equals("North")){ 
    Stud.moveNorth();   
}
else if (options.equals("South")){
    Stud.moveSouth();
}
else if (options.equals("West")){
    Stud.moveWest();
}
else if (options.equals("East")){
    Stud.moveSouth();
}
4

1 回答 1

1

你需要int compareTo(String anotherString)

JOptionPane 还返回您需要存储的值。

像这样

int optionChosen = JOptionPane.showOptionDialog(null, p + " " + Stud.distance(Comp) + " away" +  
    " Which way do you want to move?", "" + p + " is at " + Stud.getX() + ", " + Stud.getY() ,  
    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
    null, options, options[0]);

if (options[optionChosen].compareTo("North") == 0){ 
    Stud.moveNorth();   
}

或者,您可以使这更简单,并使用intJOptionPane 返回的值来选择方向。

像这样:

if (optionChosen == 0){ 
    Stud.moveNorth();   
}
else if(optionChosen == 1){
    Stud.moveSouth();
}
...and so on.
于 2012-12-07T22:04:33.800 回答