Home > Back-end >  NullReferenceException? Why?
NullReferenceException? Why?

Time:02-19

I try to calculate the total collective age of my passengers in calc_total_age() this works before I add a passenger and writes out "0". However when I add a passenger I get NullReferenceException, I have tried different things but I just can't wrap my head around what I'm doing. I need a little shove in the right direction and maybe and explanation of what the he** I am doing and I don't know what my GetAge() does either really I have tried to call it but it doesn't seem to work. This is all my code:

using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program {
  public static void Main (string[] args) {

    //Console.Clear();
    Console.WriteLine("Hi, welcome to the Buss-Simulator!");
    Console.ReadKey();
   

   var mybus = new Bus();
   mybus.Run();

   Console.ReadKey();
   
  }
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;

class Bus {

    public int total_passengers = 0;
    public Passenger[] info_passengers;
    public int totalAge = 0;
    public int totalSeats = 25;
    
    

    public void Run()
    {
      
      info_passengers = new Passenger[25];

      string [] menu = new string[]{"1. Pick up passenger.", "2. Show who's on the bus.", "3. Calculate total age of passengers"};
      int MenuSelect = 0;
    
      while (true)
      {
        Console.Clear();
        Console.WriteLine("What do you want to do?");
        Console.WriteLine();
        Console.CursorVisible = false;
        
        if (MenuSelect == 0)
        {
          Console.WriteLine(menu[0]   " ⭅");
          Console.WriteLine(menu[1]);
          Console.WriteLine(menu[2]);
        }
        else if(MenuSelect == 1)
        {
          Console.WriteLine(menu[0]);
          Console.WriteLine(menu[1]   " ⭅");
          Console.WriteLine(menu[2]);
        }
        else if(MenuSelect == 2)
        {
          Console.WriteLine(menu[0]);
          Console.WriteLine(menu[1]);
          Console.WriteLine(menu[2]   " ⭅");
        }
        
        var keyPressed = Console.ReadKey();

        if(keyPressed.Key == ConsoleKey.DownArrow && MenuSelect != menu.Length -1)
        {
          MenuSelect  ;
        }
        else if (keyPressed.Key == ConsoleKey.UpArrow && MenuSelect >= 1)
        {
          MenuSelect--;
        }
        else if (keyPressed.Key == ConsoleKey.Enter)
        {
          switch (MenuSelect)
          {
            case 0:
              add_passengers();
              break;
            case 1:
              print_passengers();
              break;
            case 2:
              calc_total_age();
              break;
          }
        }
      }
    }


  public void add_passengers()
  {
    if (total_passengers == 25)
    {
    Console.WriteLine("\nBus is full!");
    System.Threading.Thread.Sleep(2000);
    return;
    }

    try
    {
      Console.WriteLine("\nType the name, age & gender of your passenger.");

      Console.Write("\nName: ");

      string name = Console.ReadLine();

      Console.Write("\nAge: ");

      int age = Convert.ToInt32(Console.ReadLine());

      Console.Write("\nGender: ");

      string gender = Console.ReadLine();

      Passenger passenger = new Passenger(aName: name, aAge: age, aGender: gender);

      Array.Resize(ref info_passengers, info_passengers.Length   1);

      info_passengers[info_passengers.Length - 1] = passenger;
    }

    catch (Exception e)
    {
      Console.WriteLine("\nFollow instructions.");
      System.Threading.Thread.Sleep(2000);
      return;
    }

    total_passengers  ;
    Console.WriteLine("You boarded 1 Passenger."   "\nThere are "   (totalSeats - total_passengers)   " seats left.");
    System.Threading.Thread.Sleep(2000);
    return;
  }
    
  
  
    public void print_passengers()
    {
      Console.WriteLine();
      foreach (var i in info_passengers)
      {
        Console.WriteLine(i);
      }
      Console.ReadKey();
    }

    public void calc_total_age()
    {
      for (int i = 0; i < total_passengers; i  )
      {
        totalAge  = info_passengers[i].age;
      }
    Console.WriteLine(totalAge);
    Console.ReadKey();
    } 
}
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;

class Passenger{

  public string name;
  public int age;
  public string gender;

  public Passenger(string aName,  int aAge, string aGender)
  {
    name = aName;
    age = aAge;
    gender = aGender;
  }
  
  public override string ToString()
  {
    return string.Format($"This is {name}, {gender}, {age} years old.");
  }

  public int GetAge()
  {
    return age;
  }
  

}

CodePudding user response:

you don't need to resize info_passengers array since it is enough for total passangers. When you add an extra array cell, you add a passanger to the end of arry, but you still have the empty cells in the beginnig of array with null that are causing the exception.

so remove this code

 Array.Resize(ref info_passengers, info_passengers.Length   1);

and fix this

 total_passengers  ;
 info_passengers[ total_passengers-1] = passenger;

and don't forget to remove total_passengers ; from here

 Console.WriteLine("You boarded 1 Passenger."   "\nThere are "   (totalSeats - total_passengers)   " seats left.");

and add totalAge=0 in calc_total_age

public void calc_total_age()
    {
       totalAge=0;
      for (int i = 0; i < total_passengers; i  )
      {
        totalAge  = info_passengers[i].age;
      }

and it is not a very good idea to hide errors in your catch blok. I would make it

catch (Exception e)
    {
      Console.WriteLine("\n Error!!! "   e.Message);
      System.Threading.Thread.Sleep(2000);
      return;
    }

CodePudding user response:

The answer to this one is very simple!

You declare:

public Passenger[] info_passengers;

This actually creates a pointer to a Passenger array, which (like all pointers) is initially null. It does not create the actual array itself.

When your code comes to call:

Array.Resize(ref info_passengers, info_passengers.Length   1);

the method Resize expects the array parameter to point to an array. However, info_passengers is still null. So you get the exception.

I think all you need to do is to initialise info_passengers to an new empty array, like this:

public Passenger[] info_passengers = new Passenger[]();

and then I think it'll all work.

  • Related