Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array Indexing

    class anEvent{ 
  String number;
  String dueTime;
 }



public static void main(String args[]) {
      int x = args.length / 2;
      int y = args.length;
      anEvent [] order = new anEvent [x];
      for(int i=0; i<x; i++){
       if(i==0){
        order[i].number = args[0]; //Line(#)
        order[i].dueTime = args[1];
       } else if ( i % 2 == 0){
       order[i].number = args[i];
       order[i].dueTime = args[i];
       } else if ( i % 2 != 0){
        order[i].number = args[i+1];
        order[i].dueTime = args[i+1];
       } else if ( i == x -1){
        order[i].number = args[x-1];
        order[i].dueTime = args[x-1];
       }

      }

Java complains that a Null Pointer exceptuion is present at line # in the above snippet.

What's the matter?

ps: I know that the snippet can be cleaned up but there should be no problem at all on line #

like image 680
frantic Avatar asked Dec 02 '25 01:12

frantic


2 Answers

When an array is created, all the array elements are null. In your case, you need to fill the array with new anEvent() instances.

like image 90
Chris Jester-Young Avatar answered Dec 03 '25 16:12

Chris Jester-Young


Make the first line of your for-loop:

order[i] = new anEvent();

As is, you are not initializing anything in the array (they're all null), so when you try to access the fields you get that exception.

like image 25
Sapph Avatar answered Dec 03 '25 14:12

Sapph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!