0

I wrote a simple code to provide a mini system for a game ticket reservation and while running my project i got some errors in the following function as shown below in the code

Code:

public void reverseTicket(int seatNum,int gameCode,int categ,int price) 
{
    checkseat(seatNum);
    for(int i=0;i<=seat.counter;i++)
    {
    if(set[seat.counter].available==true)
    {

     gameCode=gameCode;
     set[seat.counter].number=seatNum;
     set[seat.counter].category=categ;
     set[seat.counter].price=price;
        seat.counter++;
        break;

    }
    else
    {
        System.out.println("is seat number is full");   
    }


    } 
}
    public void checkseat(int num){
 for(int i=0;i< set.length;i++)
 {
     if(set[i].number==num)
     {
         System.out.println("Seat is reserved");
         set[i].available=false;
         break;
     }    
 }

}

the errors appeared:

Exception in thread "main" java.lang.NullPointerException
at sports.game.tickt.fans.checkseat(SportsGameTickt.java:199)
at sports.game.tickt.fans.reverseTicket(SportsGameTickt.java:170)

How can I fix that please?

  • Change the code so `set` is not null, and all the elements of `set` are not null. Since you haven't shared the code that declares `set` or the code that is supposed to build the `set` array, we can't help more than just saying that. – Andreas Jun 09 '20 at 17:39
  • There isn't enough code to identify the issue. The exception says that the line with the issue is 199. I guess it is ether the `for` line, which would mean the `set` is not initialized, or if is the `if` line, which means the one of the elements is null. – hidralisk Jun 09 '20 at 17:49

1 Answers1

0

You should add null whenever you use any variables

    public void checkseat(int num) {
        if (null == set) { // Return if set array is null
            return;
        }
        for (int i = 0; i < set.length; i++) {
            if (null != set[i] && set[i].number == num) { // null check for set[i]
                System.out.println("Seat is reserved");
                set[i].available = false;
                break;
            }
        }
    }
QuickSilver
  • 3,915
  • 2
  • 13
  • 29