Question Clearing array and calcing array?

Netsid

Member
Joined
Feb 10, 2020
Messages
21
Programming Experience
Beginner
Im doing a school project and i have managed to come so far but now im stuck again i can´t figure out this last 2 things. This is my first project in C#, well programming at all. What im trying to do is get the methods for "emptying bus" and "calcpass" to work properly but im stuck right here. Line 42 and 59 is starting points, i really apriciate any help i can get! =)

thebus:
using System;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)     //main method, runs Bus
        {   //visuals
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.SetWindowSize(63, 39);
                                                //runs bus class
            var runbus = new Bus();
            runbus.Run();
        }
    }
    class Bus
    {
        private const int V = 25;                            //variable for max passengers
        private int Y = 0;                                  //variable for keeping track of passengers
        private Passenger[] passengers = new Passenger[V]; // Initializing array of passengers

        public void addpass()                            //method for adding passengers
        {
            if (Y < 25)                                  //if statement informs if bus is full
            {
                Console.WriteLine("Type name of the passenger and press [Enter]");
                string nname = Console.ReadLine();
                Console.WriteLine("Type age of the passenger and press [Enter]");
                double nage = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine("Type sex m/f of the passenger and press [Enter]");
                string nsex = Console.ReadLine();
                passengers[Y] = (nname, nage, nsex);
                Y++;
            }
            else
            {
                Console.WriteLine("The bus is full");
            }

        }
        public void emptybus()                        //method for emptying bus XXXXXX not working
        {
            if (Y > 0)
            {
                Array.Clear(passengers, 0, Y);
                Console.WriteLine("Press any key to continue");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("Bus is empty");
                Console.WriteLine("Press any key to continue");
                Console.ReadKey();
            }

        }
        //  public double calc_age() =>  / Bus.Y;
        public void calcpass()                           //method for calculating passenger average age XXXXXXX not working
        {
            double totage = 0;
            for (double i = 0; i < passengers.Length; i++)
            {
                Console.WriteLine(passengers[Y]);
                totage = passengers[Y].age;
                double midage = (double)totage / passengers.Length;

                Console.WriteLine($"midage is {midage}");
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
                this.Run();
            }
        }
        public void showlist()                          //method with forloop to show passenger list
        {
            for (int i = 0; i < Y; i++)
            {
                Console.WriteLine($"Name: {passengers[i].name} Age: {passengers[i].age} Sex: {passengers[i].sex}");
            }
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
        public void Run()
        {
            int choice = 0;
            var _exiter = new Exit();                     //variable for starting class for exiting program 
            do                                            //do-while to loop menu
            {
                Console.Clear();                         //keeps menu clean
                Console.WriteLine("" + Y + " passengers on bus.");
                Console.WriteLine("Welcome, what do you need to do?");
                Console.WriteLine("Please choose a number from the menu and press enter.");
                Console.WriteLine("1. Add passenger");
                Console.WriteLine("2. Empty bus");
                Console.WriteLine("3. Show passenger list");
                Console.WriteLine("4. Calculate average age");
                Console.WriteLine("5. Close Program");
                try                                       // try block to catch bad input
                {
                    choice = int.Parse(Console.ReadLine());
                }
                catch
                {
                    Console.WriteLine("Please choose 1-4");
                }                                        //switch statement menu
                switch (choice)
                {
                    case 1:
                        this.addpass();
                        break;
                    case 2:
                        this.emptybus();
                        break;
                    case 3:
                        this.showlist();
                        break;
                    case 4:
                        this.calcpass();
                        break;
                    case 5:
                        _exiter.Run();
                        break;
                    default:
                        Console.WriteLine("Try again.");
                        break;
                }
            } while (choice != 0);
        }
    }
    class Passenger                                    //passenger class containing variabels, parameters and constructor
    {
        public string name;
        public double age;
        public string sex;

        public Passenger(string name, double age, string sex)          //constructor passenger
        {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        public double getage()                                  //method to return age
        {
            return age;
        }

                                                            //Tuple constructor for returning values
        public static implicit operator Passenger((string nname, double nage, string nsex) v)
        {
            return new Passenger(v.nname, v.nage, v.nsex);
        }

    }
    class Exit                                   //Class for closing program
    {
        public void Run()
        {
            Console.Clear();
            Console.Write("Press any key to exit.");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }
}
 
Emptying bus: What does variable Y represent? What is the value of Y after emptying bus? Is "Y" a good name for such a variable?

Calculating average: What are the two values you need to calculate the average age of all passengers?
 
Emptying bus: What does variable Y represent? What is the value of Y after emptying bus? Is "Y" a good name for such a variable?

Calculating average: What are the two values you need to calculate the average age of all passengers?

The Y represent the number of passengers currently on the bus, im not sure its a good name, as i said im very new to this.
I only need to calculate the average age of all passengers, nothing else. I know it doenst make much sense but its for school so it doesnt have too i guess! =)
Thank you for answering.
 
If you are adding passengers, you are incrementing Y. (See line 34.) Wouldn't it stand to reason that if you empty the bus, then there would be no more passengers and therefore you need to set Y back to zero?

Using good names for variables is very important. It makes it easier for you and others to understand the code. Right now with your use of Y, you and readers of your code need to mentally translate that as "count of passengers". So why not just name the variable PassengerCount instead?
 
As for @JohnH's question about what two values you need to calculate the average age, he is trying to get you to think about the steps you need to take. If you were doing this on paper, how would you compute the average age? You would do the same procedure with code.
 
Change :
C#:
        private int Y = 0;
To :
C#:
        private int Y { get { return Get_PassengerCount(); } set { value = Get_PassengerCount(); } }

Then add this to your Bus class :
C#:
        private int Get_PassengerCount()
        {
            int num = 0;
            foreach (Passenger _passenger in passengers)
            {
                if (_passenger != null)
                num++;
            }
            return num;
        }
And then change line 34 and anywhere else where you increment integer from :
C#:
Y++;
To :
C#:
                Y = Get_PassengerCount();
You will find this will help get the total passengers count from the class object of passenger, but you have lots of room for tidying up.

Edit : Fixed text typo
 
Last edited:
You will also notice that the code changes I provided will also change your Y value to equal exactly how many passengers are actually on the bus instead of minus & addition of integers, as this pulls each passenger from your passengers object.
 
Ok thanks guys im going to try this, is it possible to edit my original post here? Cant find the button. I forgot to reset Y after clearing the array, ill rename it for sure thats great input!
 
You do not have permission to edit your original post. And you are only allowed to edit your original post when you hit a certain post threshold. You are also only allowed to edit your original post to make minor corrections before there are replies to your topic. Otherwise, if you've made a mistake in the way of posting the wrong code. you then need to post your updated code as a reply to your initial topic.
 
In general, it is poor etiquette to edit your original post in thread based forums, specially after people have commented about something in the original post. It now makes it look like the people who responded are losing their minds because they commented on something that doesn't exist (anymore). Yes, on StackOverflow, it's common practice to iterate over multiple versions of your original question as the comments (and answers) come in to make for a better question.

While you are renaming variables, be sure to also rename V. Here's the general rule of thumb: if you need to write a comment to explain what a variable (or method, or property, or class) is used for, you should rename it so that you don't need the comment.
 
Wouldn't it stand to reason that if you empty the bus, then there would be no more passengers and therefore you need to set Y back to zero?
The changes I suggested will help with this. Being new, I assume OP didn't know how to acquire the total count of passengers from passenger[] and cast the value to their int value Y. Using something like : private int Y { get { return Get_PassengerCount(); } set { value = Get_PassengerCount(); } } will prevent the need to increment or decrease Y as this will pull the total users on the bus from the passenger object where they are stored.
 
But there's really no need to increment Y anymore, if the setter just ignores the value that is being passed to it. All you would need would be the getter.

But then the getter just calls a method called Get_PassengerCount. So the property Y:
C#:
int Y { get return Get_PassengerCount(); }
might as well just be:
C#:
int PassengerCount
{
    get
    {
        int count = 0;
        foreach (Passenger p in passengers)
        {
            if (p != null)
                count++;
        }
        return count;
    }
}
 
Anyway, taking a closer look at the average calculation, there's multiple errors. At first there's line 65 which always access the same element because V doesn't change. Then there's the logic error in the for loop which iterates over all items in the array without discriminating between null and non-null passenger objects. Than after that there is computation of the average on line 66 which uses the size of the entire array as the denominator for the average instead of just the non-null passengers.
 
But there's really no need to increment Y anymore, if the setter just ignores the value that is being passed to it. All you would need would be the getter.
Run the original code and you will see why I left the setting call there. I can't recall why i did, even though i only wrote it a few minutes ago. Lol.

I currently have four other live projects open for work as well and I'm a bit overloaded to look back at it at the moment. That's why i said :
but you have lots of room for tidying up.
You are seen the same house keeping that I was looking at which I didn't edit because I don't have time.

It looks like a fun little assignment actually. And I wish I had more time to play with it.
 
Run the original code and you will see why I left the setting call there.
Yes, because line 34 tries to increment Y. You would need the setter. Since the setter just ignores any values set to it, you might as well delete line 34.

(I realize now that I only mentioned deleting line 34 when I messaged you privately, but didn't mention it above in post #12.)
 

Latest posts

Back
Top Bottom