Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Don';无法获得此java NullPointerException的解决方案_Java_Oop - Fatal编程技术网

Don';无法获得此java NullPointerException的解决方案

Don';无法获得此java NullPointerException的解决方案,java,oop,Java,Oop,在Dotcom类中,int[]arr=位置导致错误。当我删除了,我没有得到任何错误,这是怎么回事?我得到的错误是 2线程“main”java.lang.NullPointerException中出现异常 class DotCom{ int[] arr; int numOfhits=0; void setLocation(int[] location){ int[] arr=location; } String checkGuess(in

在Dotcom类中,int[]arr=位置导致错误。当我删除了,我没有得到任何错误,这是怎么回事?我得到的错误是

2线程“main”java.lang.NullPointerException中出现异常

class DotCom{
    int[] arr;
    int numOfhits=0;
    void setLocation(int[] location){
        int[] arr=location;
    } 

    String checkGuess(int guess){
        System.out.println(guess);
        String result="miss";
        for(int i:arr){
            if (i==guess){
                 result="hit";
                numOfhits++;
                break;
                }

            if(numOfhits==arr.length){
                result="kill";
            }
        }
        System.out.println(result);
        return result;
    }
}

class TestDotCom{
    public static void  main(String[] args){
        DotCom obj=new DotCom();
        int[] location ={1,2,3};
        obj.setLocation(location);
        int userGuess=2;
        String testResult="fail";
        String result=obj.checkGuess(userGuess);

        if(result=="hit"){
            testResult="passed";
            }

        System.out.println(testResult);
    }
}   

我不明白程序出了什么问题。

setLocation()
中:
int[]arr=location应为
arr=位置。您正在用本地声明覆盖全局
arr

在此处删除int arr[]的新声明:

    at DotCom.checkGuess(DotCom.java:12)
    at TestDotCom.main(TestDotCom.java:8) 

您是否打算将
arr
声明为
setLocation
方法中的新变量?因为当前您在类内的
int[]arr
变量中没有存储任何内容,所以当您尝试访问它时,您会得到空值。尝试删除
setLocation
方法中
arr
上的
int[]
声明。@jitendra为什么要获取另一个变量?您只需初始化全局变量
arr
,即代码第2行的变量。然后,这个问题就会得到解决,你的程序也会很好,除非你在其他地方有更多的问题。我可以在其他方法中使用局部变量吗?@jitendra,当然你可以使用局部变量。只需确保不要使用全局变量的相同名称命名它们(如果您覆盖了它,请注意局部变量就是在局部范围中引用的变量)。好的,我明白了!!谢谢你的帮助
void setLocation(int[] location) {
    arr = location;
}