Java空对象表单数组
所以,我有一个程序,我需要得到一个数组的对象。所以我必须检查那里的每个物体,但它显示了一个错误。我认为这是因为获取空对象不起作用。我该怎么做?我是新来的 get是一个简单的返回this.x,但我认为它是因为null而中断的Java空对象表单数组,java,arrays,object,Java,Arrays,Object,所以,我有一个程序,我需要得到一个数组的对象。所以我必须检查那里的每个物体,但它显示了一个错误。我认为这是因为获取空对象不起作用。我该怎么做?我是新来的 get是一个简单的返回this.x,但我认为它是因为null而中断的 public Sunflower get(int x, int y) { boolean found=false; Sunflower sun = null; for(int i=0; i<MAX && found==false; i++) {
public Sunflower get(int x, int y) {
boolean found=false;
Sunflower sun = null;
for(int i=0; i<MAX && found==false; i++) {
if(array[i].getX() == x && array[i].getY() == y) sun= array[i];
}
return sun;
}
}
我知道如果它死了什么也找不到就没用了,但是我试着把它写在if里面,什么都没有。。。所以不知道。在尝试访问成员变量之前,应该检查null元素。 您还可以使用break而不是boolean found 公共向日葵获取(整数x,整数y){
Sunflower sun=null;
对于(int i=0;i,如果要检查所有元素,则应使用array.length获取数组的最大索引。此外,还可以检查元素是否为null并跳过它:
public Sunflower get( int x, int y ) {
boolean found = false;
Sunflower sun = null;
for (int i = 0; i < array.length && found == false; i++) {
if (array[i] != null &&
array[i].getX() == x && array[i].getY() == y) {
sun = array[i];
found = true;
}
}
return sun;
}
public Sunflower get(int x,int y){
布尔值=false;
向日葵太阳=零;
for(int i=0;i
给出代码的工作示例,并进行了一些改进:
public class Main {
public static class Sunflower {
private int x, y;
Sunflower(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public static class Getter {
private Sunflower[] array = {new Sunflower(1, 0), new Sunflower(0, 1), null, new Sunflower(3, 1)};
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}
}
public static void main(String[] args) {
Getter getter = new Getter();
assert getter.get(1, 0) != null;
assert getter.get(1, 0) != null;
assert getter.get(3, 1) != null;
assert getter.get(3, 2) == null;
}
}
您最感兴趣的功能是:
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}
变化:
foreach循环
检查该值是否为空
返回而不设置found
变量
否则返回null
让我们来看看这个错误。另外,我们不知道如何创建<代码>数组>代码>。你也可以发布错误日志吗?这可能会给人们的遗传信息提供更多的信息。MAX大于ARARY.Load。如果你想让人们阅读,请考虑更仔细地编码你的代码。只需把错误本身添加到这个问题上。它会有帮助。哦,我明白了。所以跳过空值。那可能有用。谢谢你,老兄,我会试试的。
public class Main {
public static class Sunflower {
private int x, y;
Sunflower(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
}
public static class Getter {
private Sunflower[] array = {new Sunflower(1, 0), new Sunflower(0, 1), null, new Sunflower(3, 1)};
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}
}
public static void main(String[] args) {
Getter getter = new Getter();
assert getter.get(1, 0) != null;
assert getter.get(1, 0) != null;
assert getter.get(3, 1) != null;
assert getter.get(3, 2) == null;
}
}
Sunflower get(int x, int y) {
for (Sunflower s : array) {
if (s == null) continue;
if (s.getX() == x && s.getY() == y) return s;
}
return null;
}