NullPointerException at int array in Java Project

I am creating a method which will take int n as a parameter, convert a previously initialized String into an integer array, add 1 to each index n times, create a new char array from each increment of the int array via casting, then convert all n char arrays into new strings and print them to the screen.

Netbeans throws a NullPointerException in my current project, and I'm not sure why. Could someone explain why this error is present and what I ought to do to fix it?

Relevant Class: https://www.dropbox.com/s/gv02i1traulg8kp/StringShifter.java
Class containing Main Method: https://www.dropbox.com/s/ymon96ovv4c2lnf/CodeBreaker.java

Error:
Exception in thread "main" java.lang.NullPointerException
at Project5.StringShifter.shift(StringShifter.java:35)
at Project5.CodeBreaker.main(CodeBreaker.java:18)

Jon Skeet
people
quotationmark

Look at your code:

int[] a = null; 
char[] b = null; 
int r = 0; 

for (int i = 0; i <= text.length(); i++) { 
    a[i] = text.charAt(i); 
}

a is null - you've explicitly set it to null. So

a[i] = text.charAt(i);

will fail with a NullReferenceException - it's bound to. You'd need to initialze a to refer to an array, e.g.

int[] a = new int[text.length()];

You also need to change your upper bound - as when i is text.length(), text.charAt(i) will throw an exception. So you want:

int[] a = new int[text.length()];
for (int i = 0; i < text.length(); i++) { 
    a[i] = text.charAt(i); 
}

It's not clear why you want an int[] at all though. It would be simpler to use:

char[] chars = text.toCharArray();
for (int i = 0; i < text.length(); i++) {
    chars[i] = (char) (chars[i] + 1);
}

Also:

  • There's no point in going over the loop multiple times - just add n instead of 1
  • There's no point in creating a new string on every iteration; just do it at the end

people

See more on this question at Stackoverflow