Java 关于JOptionPane取消选项
我不能两次暗示方法的取消选项。(足球的第一个输入对话框和第二个输入对话框)当我单击取消按钮时,Java 关于JOptionPane取消选项,java,swing,nullpointerexception,joptionpane,Java,Swing,Nullpointerexception,Joptionpane,我不能两次暗示方法的取消选项。(足球的第一个输入对话框和第二个输入对话框)当我单击取消按钮时,NullPointerException出错。有什么想法吗 public void RandomDistribution() { String[] gametypes = {"NBA", "Euroleague", "NCAA", "NHL", "Football" }; String question = "Choose the Game"; String title = "
NullPointerException
出错。有什么想法吗
public void RandomDistribution() {
String[] gametypes = {"NBA", "Euroleague", "NCAA", "NHL", "Football" };
String question = "Choose the Game";
String title = "Memory Game";
ImageIcon entry = new ImageIcon(getClass().getResource("background.jpg"));
String c = (String) JOptionPane.showInputDialog(null, question, title,
JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);
if (c.equals("Football")) {
String[] f_level = {"Easy", "Normal", "Hard"};
String question_f = "Choose the Level";
String title_f = "Memory Game - Football";
String c2 = (String) JOptionPane.showInputDialog(null, question_f, title_f,
JOptionPane.PLAIN_MESSAGE, null, f_level,f_level[2]);
if (c2.equals("Easy")) {
c = "Football1";
} else if (c2.equals("Normal")) {
c = "Football2";
} else if (c2.equals("Hard")){
c = "Football3";
}
}
for (int i = 0; i < 64; i++) {
PicOfCells[i] = (int) (Math.random() * 64) + 1;
for (int j = 0; j < i; j++) {
if (PicOfCells[i] == PicOfCells[j] && i != j && i != 0) {
--i;
}
}
}
for (int i = 0; i < 64; i++) {
PicOfCells[i] = (PicOfCells[i] % 32);
PicOfAllCells[i] = new ImageIcon(getClass().getResource(PicOfCells[i] + 1 + c +".gif"));
}
StartGame.doClick();
}
公共分布(){
String[]游戏类型={“NBA”、“欧洲联盟”、“NCAA”、“NHL”、“足球”};
String question=“选择游戏”;
String title=“记忆游戏”;
ImageIcon条目=新的ImageIcon(getClass().getResource(“background.jpg”);
String c=(String)JOptionPane.showInputDialog(null、疑问、标题、,
JOptionPane.PLAIN_消息、条目、游戏类型、游戏类型[4];
如果(c.equals(“足球”)){
字符串[]f_level={“简单”、“正常”、“困难”};
字符串问题\u f=“选择级别”;
String title_f=“记忆游戏-足球”;
String c2=(String)JOptionPane.showInputDialog(null,问题,标题,
JOptionPane.PLAIN_消息,null,f_级别,f_级别[2]);
如果(c2.等于(“容易”)){
c=“足球1”;
}else如果(c2.等于(“正常”)){
c=“足球2”;
}else if(c2.等于(“硬”)){
c=“足球3”;
}
}
对于(int i=0;i<64;i++){
PicOfCells[i]=(int)(Math.random()*64)+1;
对于(int j=0;j
如果我理解正确,您的问题是,当您取消两个对话框中的一个时,您会得到一个NullPointerException
查看解释了当用户取消输入时将返回什么:
返回:
用户的输入,或null表示用户取消了输入
所以你的代码
String c = (String) JOptionPane.showInputDialog(null, question, title,
JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);
当用户取消输入时,将c
设置为null
。因为你知道
if (c.equals("Football")) {
在下一行中,您试图调用null
引用上的方法equals(…)
,这是不可能的,并且会导致出现NullPointerException
。为了防止引发异常,您需要检查c
中的null
,例如:
if (c == null) {
// do whatever you want to do when the user canceled input
} else if (c.equals("Football")) {
当然,
c2
…;-)也是如此 c==null
和c2==null
检查在哪里?