【问题标题】:How to implement a search feature using variables from another class (C#)?如何使用来自另一个类(C#)的变量来实现搜索功能?
【发布时间】:2021-01-17 15:30:14
【问题描述】:

我正在做一个小项目,用户将有关电影的信息输入到数组中,然后可以搜索标题以找出先前输入的信息。 但是,我当前的搜索功能在代码末尾返回:

System.String[]'s age rating is System.Int32[]
System.String[]'s genre is System.String[]
System.String[]'s rating is System.Int32[]

如何让代码加载所需的信息而不是当前返回的信息? 请参阅下面的代码。

static void Movie(string[] MovieTitle, string[] Genre, int[] AgeRating, int[] Rating)
                {
                for (int i = 0; i < Rating.Length; i++)
                {
                    Console.WriteLine("What is the title of the movie?");
                    MovieTitle[i] = (Console.ReadLine());
                    Console.WriteLine("What is the age rating of the movie?");
                    AgeRating[i] = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("What is the genre of the movie?");
                    Genre[i] = (Console.ReadLine());
                    Console.WriteLine("What is the user rating of the movie?");
                    Rating[i] = Convert.ToInt32(Console.ReadLine());
                    
    
                }
            }
            
            static void Main()
            {
                string[] MovieTitle = new string [5];
                int[] AgeRating = new int [5];
                string[] Genre = new string [5];
                int[] Rating = new int [5];
                int position;
                string search;
    
                Movie(MovieTitle, Genre, AgeRating, Rating);
    
                Console.WriteLine("What movie do you want to see?");
                search = Console.ReadLine();
                position = Array.IndexOf(MovieTitle, search);
                Console.WriteLine(MovieTitle + "'s age rating is " + AgeRating);
                Console.WriteLine(MovieTitle + "'s genre is " + Genre);
                Console.WriteLine(MovieTitle + "'s rating is " + Rating);
            }
        }
    }

【问题讨论】:

    标签: c# arrays search


    【解决方案1】:

    您不是在访问单个项目,而是在打印信息时使用数组本身。您需要使用position 来查找数组中的特定元素:

    Console.WriteLine(MovieTitle[position] + "'s age rating is " + AgeRating[position]);
    Console.WriteLine(MovieTitle[position] + "'s genre is " + Genre[position]);
    Console.WriteLine(MovieTitle[position] + "'s rating is " + Rating[position]);
    

    您可能还需要添加绑定检查,因为如果在数组中未找到该元素,IndexOf 将返回 -1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      相关资源
      最近更新 更多