-2
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);
    }
}   

in Dotcom class the int[] arr=location causes error. When I remove that i doesn't get any error what is going on over here? The error I get are

2 Exception in thread "main" java.lang.NullPointerException

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

I don't get it what's wrong with the program.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jitendra
  • 11
  • 3
  • Are you meaning to declare the `arr` as a new variable in the `setLocation` method? Because currently you aren't storing anything in your `int[] arr` variable inside your class so when you try to access it you are getting your null points. Try removing the `int[]` declaration on `arr` in the `setLocation` method. – Michael Platt Jun 05 '17 at 18:50

2 Answers2

0

In setLocation(): int[] arr=location; supposed to be arr=location;. You're overriding the global arr with a local one.

SHG
  • 2,516
  • 1
  • 14
  • 20
  • @jitendra Why do you want to take another variable? You just have to initialize the global variable `arr`, the one from line 2 in your code. Then, this problem will be resolved, and your program will be fine unless you have more problems in other places. – SHG Jun 05 '17 at 19:27
  • can i use local variables in other method? – jitendra Jun 05 '17 at 19:29
  • @jitendra, Of course you can use local variables. Just make sure not to name them with the same name of a global variable (and if you do override it, be aware that the local var is the one referred in a local scope). – SHG Jun 05 '17 at 19:31
  • okay i get it!! thank you for your help – jitendra Jun 05 '17 at 19:40
0

Remove the new declaration of int arr[] here:

void setLocation(int[] location) {
    arr = location;
}
Davis Molinari
  • 741
  • 1
  • 5
  • 20