0

So I need to locate where the "Nut" string is stored at. I thought my code would work just fine but obvious the ide just keep throwing me an error.

Random rd = new Random();
String[] hidingSpots = new String[100];
hidingSpots[rd.nextInt(hidingSpots.length)] = "Nut";
System.out.println("The nut has been hidden ...");
int nutLocation = 0;
while (nutLocation < hidingSpots.length) {
    if (hidingSpots[nutLocation].equals("Nut")) {
        System.out.println("Found it! It's in spot# " + hidingSpots[nutLocation]);
    }
    nutLocation++;
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
FeCH
  • 133
  • 3
  • 15
  • 2
    `the IDE just keeps throwing me an error` - it would be useful for us to know what that error was – m_callens Jan 29 '17 at 22:29
  • Its an semantic error so there arent really any useful information . Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project HiddenNuts: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1] To see the full stack trace of the errors, re-run Maven with the -e switch. Re-run Maven using the -X switch to enable full debug logging. For more information about the errors and possible solutions, please read the following articles: [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException – FeCH Jan 29 '17 at 22:32
  • that error has nothing to do with your code. It's a maven error. – m_callens Jan 29 '17 at 22:33

1 Answers1

2

If I had to guess, you're probably getting a NullPointerException because you only initialized one string within the hidingSpots array. When you first created the array of size 100, all the elements in the string array are null until you initialize them with something. Therefore, this line

if(hidingSpots[nutLocation].equals("Nut"))

is causing the error right now because 99 of the elements in hidingSpots are currently null and you can't compare a string to null.

Strings are objects, so their default values in arrays, like any other object, is going to be null. This is different than the default values of primitive types in arrays. For example, an int array of size 100 would contain 100 zeros by default.

Chris Gong
  • 8,031
  • 4
  • 30
  • 51
  • Thanks, thats the problem! instead of checking if its nut i just check if its not null. – FeCH Jan 29 '17 at 22:39