Im getting a NullPointerException error on my code. I really dont know why it is happenning. This's only a sample of the code, i can post the full version if needed.

private static final Scanner in=new Scanner(System.in);
public static void main(String[] args) {
   int n1=lerTamanho();
   String [] vec1=new String [n1];
   readVector(vec1); -> Line 11 
}

private static int lerTamanho() {
    System.out.print("Number: ");
    int num=in.nextInt();
    while (num<=0) {
        System.out.print("Error! Number: ");
        num=in.nextInt();
    }
    return num;
}

private static void readVector(String vec[]) {
    int cont=0;
    String s;
    do  {  
        System.out.print("Name: ");
        s=in.nextLine();
        if (validate(s,vec)) { -> Line 30
            vec[cont]=s;
            cont++;
        } else {
            System.out.println("That name already exists!");
        }
    } while (cont<vec.length);
    }
private static boolean validate(String s, String vec[]) {
    boolean success=true;
    for (int i=0; i<vec.length; i++) {
        if (vec[i].equalsIgnoreCase(s)) { >-> Line 44
            return !success;
        }
    }
    return success;
}

Error I'm getting:

Exception in thread "main" java.lang.NullPointerException
at javaapplication63.JavaApplication63.validate(JavaApplication63.java:41)
at javaapplication63.JavaApplication63.lerVetor(JavaApplication63.java:30)
at javaapplication63.JavaApplication63.main(JavaApplication63.java:11)
有帮助吗?

解决方案

By default, all the elements in the String[] are initialized with null. The NullPointerException is thrown on this line:

if (vec[i].equalsIgnoreCase(s))

In order to fix it, assign the elements with values, before validating

其他提示

When you make a new array, ie String [] vec1=new String [n1];, the elements inside the array are initialized to null. Thus, when you try to access vec[i].equalsIgnoreCase(s) in

if (vec[i].equalsIgnoreCase(s)) {

you get a NPE.

   String [] vec1=new String [n1];

This statement initializes the array - it does not initialize the individual buckets of the array. For that you can walk the array in a look and set them explicitly.

 for (String s : vec) {
     s = "Some String"; //or new String()
 }

Switch vec[i].equalsIgnoreCase(s) to s.equalsIgnoreCase(vec[i])

You have created an array with below code.

String [] vec1=new String [n1];

It only creates an array with n1 elements, but all values in those elements are null.

You can try below and see.

int n1=lerTamanho();
String [] vec1=new String [n1];
for (int i=0; i < n1; i++) {
    vec1[i]= "SOME-STRING-TO-THIS-ELEMENT";
}
readVector(vec1);

NPE comes from vec[i].equalsIgnoreCase(s) where vec[i] is null.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top