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 the Null Pointer exception is present in line # in the above snippet.

What's the matter?

ps: I know that the fragment can be cleared, but there should not be any problems on the line #

+3
source share
5 answers

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

+6
source

Make the first line of your for loop:

order[i] = new anEvent();

Like you, you do not initialize anything in the array (they are all equal to zero), so when you try to access the fields, you get this exception.

+1
source

, " ", :

public class Thing {
    private String number;
    private String dueTime;

    public Thing(String number, String dueTime) {
        this.number = number;
        this.dueTime = dueTime;
    }

    public static void main(String args[]) {
        int x = args.length / 2;
        Thing[] order = new Thing[x];
        for (int i = 0; i < x; i++) {
            if (i == 0) {
                order[i] = new Thing(args[0], args[1]);
            } else if (i % 2 == 0) {
                order[i] = new Thing(args[i], args[i]);
            } else if (i % 2 != 0) {
                order[i] = new Thing(args[i + 1], args[i + 1]);
            }
        }
    }
}

"anEvent" Java , . "" , . else if , i % 2 , , . , , , . .

+1

NullPointerException , , .

Java ... , objects null

, :

Object o = null;
o.toString(); // <- NullPointerException ( think of null.toString() )

. , "" null .

:

Object[] array = new Object[10];

:

 [null,null,null,null,null,null,null,null,null,null]

, :

array[0].toString(); // or  order[i].number in your specific example... 

, :

null.toString();  // or null.number  <-- NullPointerException.

, :

for(int i=0; i<x; i++){
    order[i] = new anEvent();
    ...
    ...

, .

. Java , :

class AnEvent {
....

, , java , 4 .

+1

anEvent, (order []), .

and there is also a simpler array for your case:

List events = new ArrayList(x);
for(int i=0; i<y; i+=2){
  anEvent event = new anEvent();
  anEvent.number = args[i];
  anEvent.dueTime = args[i+1];
  events.add(event);
}
anEvent[] order = events.toArray();
0
source

Source: https://habr.com/ru/post/1733060/


All Articles