NullPointerException at int array in Java Project

徘徊边缘 提交于 2019-12-25 01:47:00

问题


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)


回答1:


Your problem is here:

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

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

a is set to point to null, and then you try to assign a value to a[i] (which currently does not have a place in memory), which will give you a NullPointer.




回答2:


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



回答3:


You define int[] a = null and never initialize it.

When you try to access it in a[i] = text.charAt(i); you get the NullPointerException.

You can solve you issue adding a initialization:

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


来源:https://stackoverflow.com/questions/19847138/nullpointerexception-at-int-array-in-java-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!