0

I am trying to write a program that lets the user input the size of their class into an array, and then find the average of all the classes.

When I run the program, it prints out the stuff I input into the array, but then it gives me a NullPointerException.

Code:

public void getinput() { //
    String dog="dog";
    boolean done=true;
    int x=0;
    int avg=0;
    int z=0;
    Scanner scan = new Scanner(System.in);
    String [] cs = new String [100];
    while(done){
        System.out.println("Enter the size of one class. When you are done, enter 'quit'");//ask for class sizes 
        dog=scan.nextLine();
        cs[x]=dog;
        x++;
            if(dog.equalsIgnoreCase("Quit")){
                done=false;

    }
}

for(z=0;z<cs.length;z++) {
    if (!(cs[z].equalsIgnoreCase("quit"))&& !(cs[z]==null)){
        System.out.print(cs[z]+", ");
    }
}
for(z=0;z<cs.length;z++) {
    if (!(cs[z].equalsIgnoreCase("quit"))&& !(cs[z]==null)){
        avg=Integer.parseInt(cs[z])+avg;
        System.out.println("");
        System.out.println("The average number of students in each classroom is "+avg);
        }
}
odeng
  • 49
  • 1
  • 9
  • Basically, you need to learn how to debug. First and foremost, look at the exception stack trace (which you **should** have reproduced here) to find out exactly where the exception occurs. Then examine the values at that point to see which might null. If it's not obvious either use a debugger or insert print statements to find out the values of "suspect" variables feeding that statement. Then trace the problem variable back to where it was (or should have been) set and figure out why it's bogus. – Hot Licks Jan 10 '15 at 23:18
  • I have linked to a Q&A that has an answer that covers this in detail. (Hint ... my answer.) – Stephen C Jan 11 '15 at 00:00
  • @HotLicks thanks for the advice but i honestly don't know what that is :( i just started learning java in august but thanks for the advice! – odeng Jan 13 '15 at 02:38
  • http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Hot Licks Jan 13 '15 at 03:10

2 Answers2

1

Another simpler solution is to invert the condition using the string first, since equalsIgnoreCase already treats the null possibility:

if ("quit".equalsIgnoreCase(cs[z])){

That way you would know this part of the code wouldn't throw a NullPointerException.

0

If cs[z] can be null you should swap the order of the conditions, since cs[z].equalsIgnoreCase("quit") would throw NullPointerException when cs[z] is null :

if (cs[z]!=null && !(cs[z].equalsIgnoreCase("quit")))
Eran
  • 387,369
  • 54
  • 702
  • 768