首页 > 解决方案 > C# 检查数组是否“满”

问题描述

我有一个关于数组的问题和问题。

在下面的代码中,计划是为用户提供一个菜单,如果用户选择 nr 1,程序将要求用户输入姓名和年龄以填充数组。但是我希望代码在要求用户输入名称之前检查名称数组是否已满(这是因为名称是用户被要求输入的第一件事)。如果数组是“满的”,它应该写出类似“满”的东西,如果不是,则要求用户输入信息。

这是问题进入图片...

因为只要用户不希望退出程序(通过菜单),菜单就会循环,因此可以多次选择此选项。如果用户再次选择相同的选项,则意味着数组已满,并且无法对同一数组进行更多输入。在我当前的代码中,这个“检查”功能不起作用。我尝试了不同的解决方案,包括 if/else、bool 循环和自定义设计的方法。他们都失败了。

在 stackoverflow 上快速搜索,给出了一些想法,但没有人为我工作,虽然其中一个线程似乎是好方法,但我不明白如何构建这种方法。这是该答案的链接:检查数组是否已满(有趣的部分是“int bookCounter = 0;”

我确信有一种简单的方法可以解决这个问题,但我非常感谢您的帮助!

备注:部分代码是用瑞典语编写的,但我将所有重要部分都翻译成英文。

 public void Run()
    {
        int choice;
        do
        {

            //Menyn:

            Console.WriteLine("Hello and welcome to this awesome buss-simulator!{0}", Environment.NewLine);
            Console.WriteLine("Please choose an option in the menu below.{0}", Environment.NewLine);
            Menytexts();


            choice = CorrectEntryMenu(1, 8); //Method to make sure it's a number. Not related to this.

            switch (choice)
            {
                case 1:
                    Console.WriteLine("Welcome, please enter the passengers name:"); //lägg till passa.
                    string name = Console.ReadLine();

                    int age = CorrectEntry("We also need the persons age: "); //Another method for correct input. Not the problem.

                    add_passenger(age, name); //Sending input info to the method containing the arrays.

                    Console.WriteLine("The passenger is registered. " +
                        "Press any key to return to the manu");

                    Console.ReadKey();

                    break;

                case 2:
                    print_buss();
                    break;


            }
        } while (choice != 8);


    }

    //Metoder för betyget E

    public void add_passenger(int age, string name) //Method containing the arrays and the problems.
    {

        string[] passengername = new string[2]; //Array for all the names. temporarily set to 2 spaces. 



         //idealistically the method for checking the array is inserted here.

        for (int n = 0; n < passengername.Length; n++) //To fill array if not full
        {
            name = passengername[n];

            int[] passengerage = new int[2]; //Array for all the ages. Temporarily set to 2 spaces. 

            for (int x = 0; x < passengerage.Length; x++) //If the namearray is not full then age is entered.
            {
                age = passengerage[x]; 


            }

        }

标签: c#arraysmethodsuser-input

解决方案


您已经在 add_passenger 方法中定义了 string[] 乘客名,因此当该方法返回时它不再存在(并且添加的乘客丢失了)。

您可以先将 string[] 乘客名设为实例变量。

还:

  age = passengerage[x]; 

应该是:

  passengerage[x] = age; 

推荐阅读