我正在尝试使用for循环将我的类文件中的名称转换为String
数组,并将其显示在JOptionPane
列表菜单中。但是,我面临的是NullPointerException
,但如果我没有将String
数组声明为null
,则编译器会抱怨。
public void showWindow()
{
String[] theNames = null;
for(int i=0; i<person.length; i++)
{
if(person[i] != null)
{
System.out.println(person[i].name);
}
}
String s = (String)JOptionPane.showInputDialog(null, "Select your name and click on confirm", "Results", JOptionPane.PLAIN_MESSAGE, null, theNames, "Eric");
}
如果没有逐个列出选项值,我该如何解决这个问题呢?
答案 0 :(得分:0)
这行代码没有问题:
String [] theNames = null;
String s=(String)javax.swing.JOptionPane.showInputDialog(null, "Select your name and click on confirm","Results",
javax.swing.JOptionPane.PLAIN_MESSAGE, null, theNames, "Eric");
System.out.println(s);
注意:除非您获得theNames
,否则必须先RuntimeException
。
我注意到你班上有一个人变量。 你能解释一下为什么你把这个名字作为一个null来初始化吗?它在方法中的好处是什么?
答案 1 :(得分:0)
选项可以是任何对象的数组,但要确保toString()方法是您想要在下拉菜单中显示的方法。无需逐个列出选项,甚至无需将对象转换为字符串。例如:
public class Person {
String firstName, lastName;
public Faculty(String f, String last) {
firstName = f;
lastName = last;
}
public String toString() {
return firstName + " " + lastName;
}
}
public static void showWindow() {
Person[] guys= new Person[5];
guys[0] = new Person("Dick","Wall");
guys[1] = new Person("Tor","Norbye");
guys[2] = new Person("Chet","Haase");
guys[3] = new Person("Carl","Quinn");
guys[4] = new Person("Scott","Hanselman");
Personp = (Person) JOptionPane.showInputDialog(null,
"Pick your favorite podcaster.",
"Java Posse",
JOptionPane.QUESTION_MESSAGE, null,
guys, guys[0]);
System.out.println("You picked:" + p.toString());
}