Home > OS >  Works fine in for loop but when do manually, there's a NullPointerException error - Java
Works fine in for loop but when do manually, there's a NullPointerException error - Java

Time:06-12

I'm a beginner in Java and want to upskill myself. In my program with the for loop, it works perfectly, without errors, but when I remove the for loop and manually increment it because I only want to input once and store in array, there's a NullPointerException. It looks the same for me, the only difference is it doesn't loop, but instead increment it manually. That's why I can't figure it out. What is the problem and how can I fix it? I'm having a hard time understanding what went wrong.

public class Javaapp {
    public static void main(String[] args) {
      
        Team competitive = new Team ("Cloud9", 5, 14, 18);
        Member [] member = new Member [5];
        Scanner input = new Scanner(System.in);
        int answer = input.nextInt();
  
                for(int i=0; i<competitive.maxMember; i  ){ 
                    System.out.printf("Name:");
                    String tmpName = input.next();
                    System.out.printf("Age:");
                    int tmpAge = input.nextInt();
                    member[i] = new Member(tmpName, tmpAge);   
                    }
                for(Member m: member){
                   if (competitive.checkQualification(m) == true){ 
                       competitive.addMember(m);
                       System.out.println("You're officially part of the team");
                   }
                   else if (competitive.checkQualification(m) == false)
                        System.out.println("You did not meet the requirements");
                }
    }
}

CodePudding user response:

The issue is in this loop

for(Member m: member){
   if (competitive.checkQualification(m) == true){ // The error points in here where it says NullExceptionerror
       competitive.addMember(m);
       System.out.println("You're officially part of the team");
   }
   else if (competitive.checkQualification(m) == false)
        System.out.println("You did not meet the requirements");
}

As you have not completed the input for all the members, when you try to iterate this loop, it would work OK for the first time as there is only one member in array. But next time, as there is no member at i=1, it will give NullPointerException when it is passed to checkQualification method. Instead of for each loop, just pass member[i] to that function and after that increment value of i.

  •  Tags:  
  • java
  • Related