初学JAVA,刚在做一个练习的时候出了点问题,然后我把代码单独列出来做了个实验,但是还是不明白这到底是为什么,故来请教以下是单独拎出来的代码主要是showInputDialog按取消时这个newName的值有问题
当我直接取消的时候,这个newName返回null,没有问题
然后在空的时候按确定,弹出提示对话框,然后递归再一次弹出input对话框,再按取消的时候,这个newName就是空值,而不是null,这是为什么?忘高手指教import javax.swing.JOptionPane;public class Ex {
private String inputName(String messageInput, String title, String message) {
String newName = JOptionPane.showInputDialog(null, messageInput, title,
JOptionPane.INFORMATION_MESSAGE);
if (newName != null && newName.length() == 0) {
JOptionPane.showMessageDialog(null, message, "友情提示",
JOptionPane.INFORMATION_MESSAGE);
inputName(messageInput, title, message);
}
return newName;
}
public static void main(String[] args) {
Ex ex=new Ex();
String str=ex.inputName("aa", "bb", "aa!");
System.out.println(str);
}
}
接着,我把这个递归改成循环,就没有任何问题,无论弹出几次input,按取消永远返回nullimport javax.swing.JOptionPane;public class Ex {
private String inputName(String messageInput, String title, String message) {
String newName="";
while (newName != null && newName.length() == 0) {
newName = JOptionPane.showInputDialog(null, messageInput, title,
JOptionPane.INFORMATION_MESSAGE);
if (newName != null && newName.length() == 0) {
JOptionPane.showMessageDialog(null, message, "友情提示",
JOptionPane.INFORMATION_MESSAGE);
//inputName(messageInput, title, message);
}
}
return newName;
}
public static void main(String[] args) {
Ex ex=new Ex();
String str=ex.inputName("aa", "bb", "aa!");
System.out.println(str);
}
}

解决方案 »

  1.   

    少了一个returnimport javax.swing.JOptionPane;public class Ex {
        private String inputName(String messageInput, String title, String message) {
            String newName = JOptionPane.showInputDialog(null, messageInput, title,
                    JOptionPane.INFORMATION_MESSAGE);
            if (newName != null && newName.length() == 0) {
                JOptionPane.showMessageDialog(null, message, "友情提示",
                        JOptionPane.INFORMATION_MESSAGE);
                return inputName(messageInput, title, message);//这里返回
            }
            return newName;
        }
        public static void main(String[] args) {
            Ex ex=new Ex();
            String str=ex.inputName("aa", "bb", "aa!");
            System.out.println(str);
        }
    }