0 java arrays variables private object
不太清楚为什么这不起作用,当我尝试编译并运行它时给我一个空指针异常.我知道这是非常简单的,可能是一个愚蠢的问题,但我似乎无法搞清楚!
import javax.swing.JOptionPane;
public class Whatever
{
private int age;
private String name;
private float salary;
public Whatever ()
{
String userName = JOptionPane.showInputDialog ("What is your name?");
Whatever listData[] = new Whatever [10];
listData[6].name = userName;
}
public static void main (String [] args)
{
Whatever testWhatever = new Whatever ();
}
}
Run Code Online (Sandbox Code Playgroud)
Whatever实例数组- 都是null.
OutOfMemoryError一旦你修复它,我猜你会遇到另一个问题,因为当你调用new来初始化Whatever数组元素时,他们将构造自己的数组并调用new,依此类推,直到你得到OOM错误.
我会为你拼出来,这样你就可以得到下一个错误:
import javax.swing.JOptionPane;
public class Whatever
{
private int age;
private String name;
private float salary;
public Whatever () {
String userName = JOptionPane.showInputDialog ("What is your name?");
Whatever listData[] = new Whatever[10];
for (int i = 0; i < listData.length; ++i) {
listData[i] = new Whatever(); // This is where you'll get the OOM error. See why?
}
// You'll never get here.
listData[6].name = userName;
}
public static void main (String [] args)
{
Whatever testWhatever = new Whatever();
}
}
Run Code Online (Sandbox Code Playgroud)
你将Swing代码放在构造函数中?您是否打算将此作为如何编写错误代码的示例?
仅供将来参考,您应该在一个好的IDE中运行您的代码 - 比如市场上最好的IntelliJ--打开调试并逐步执行代码.你会在问题所在的地方很快找到答案,比在SO处告诉你更快.
所以是的,这是一个非常愚蠢的例子.希望你不是真的写这样的东西.