[英]Java Array Inside of Object
I am trying to access an array that is part of an object. 我正在尝试访问作为对象一部分的数组。
I am getting the error "Exception in thread "main" java.lang.NullPointerException at OrderedStringList.add(OrderedStringList.java:21) at Main.main(Main.java:24)" 我收到错误“ Main.main(Main.java:24)处OrderedStringList.add(OrderedStringList.java:21)处的线程“ main”中的异常java.lang.NullPointerException”
I have cut my program down to the bare bones, cutting out everything that might be interfering with the output. 我已经将程序精简了,删除了可能干扰输出的所有内容。
public class Main {
public static void main(String[] args) {
int x = 5;
OrderedStringList myList = new OrderedStringList();
myList.add(x);
}
} //end class
This code references the class OrderedStringList. 此代码引用类OrderedStringList。
public class OrderedStringList {
public int values[];
OrderedStringList(){
int values[] = new int[5];
}
public void add(int y) {
values[0] = y;
System.out.print(values[0]);
}
I assume that the numbers 21 and 24 in the error are line numbers. 我假设错误中的数字21和24是行号。 Because I have some things commented out in my original code, the code I have posted would normally have some content in the middle of it.
因为我的原始代码中有一些注释掉了,所以我发布的代码通常会在其中包含一些内容。 Line 24 in main is:
myList.add(x);
main中的第24行是:
myList.add(x);
. 。 Line 21 of OrderedStringList is:
values[0] = y;
OrderedStringList的第21行是:
values[0] = y;
. 。
I'm guessing that there is something really simple that I am missing. 我猜想我确实缺少一些简单的东西。 Anything is appreciated.
一切都赞赏。
Thanks. 谢谢。
Here 这里
OrderedStringList(){
int values[] = new int[5];
}
You shadow the class member values
. 您可以隐藏类成员的
values
。
Change this to: 更改为:
OrderedStringList(){
values = new int[5];
}
You've declared values
twice.... 您已经声明了两次
values
...。
public int values[];
OrderedStringList(){
int values[] = new int[5];
}
This commonly known as shadowing. 这通常称为阴影。
Change the initialization of the array in the constructor to something like... 将构造函数中数组的初始化更改为类似...
public int values[];
OrderedStringList(){
value = new int[5];
}
Instead... 代替...
This declares the values[]
array just inside the scope of the method. 这将在方法范围内声明
values[]
数组。
OrderedStringList(){
int values[] = new int[5];
}
If want to refer to the Class
scope use 如果要参考
Class
作用域使用
OrderedStringList(){
values = new int[5];
}
With the line int values[] = new int[5];
与行
int values[] = new int[5];
, you're declaring an entirely new int[]
that exists only in the constructor. ,您要声明一个仅在构造函数中存在的全新
int[]
。 Change it to values = new int[5];
将其更改为
values = new int[5];
. 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.