使用数组拆分方法分隔名称/数字

时间:2013-03-25 16:06:11

标签: c# arrays

我已被指示编写一个程序,该程序收集用户的保龄球分数(整数)和名称,用空格分隔,并使用Split方法将每个分类为数组。输出必须格式化以找到平均分数并将其输出到控制台,并按照从最低到最高的顺序对分数(和名称)进行排序。

除了找到用相应分数对名称进行排序的方法之外,我已经能够做所有事情。

这是我到目前为止所拥有的。为了澄清,我需要帮助为我的名字数组编写排序算法。

using System;

class Program
{
    //class variables
    const int MAX = 10;

    static void Main()
    {
        //declare array
        int[] score = new int[MAX];
        string[] name = new string[MAX];

        //program prologue
        Console.WriteLine("****************Bowling Project****************");
        Console.WriteLine("Please enter a name and a score for each player. For example 'John 145'.\nHit enter when you are done.");

        //for loop to get input
        for (int i=0; i<MAX; i++)
        {
            Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
            string input = Console.ReadLine();
            if (input == "")
            {

                break; // if nothing is entered, it will break the loop
            }
            //split the user data into 2 arrays (integer and string)
            string[] separateInput = input.Split();
            name[i] = separateInput[0];
            score[i] = int.Parse(separateInput[1]);
        }

        Console.WriteLine("\n****************Input Complete****************");

        //calculate the average score and send to the console
        CalculateScores(score);

        Console.WriteLine("The scores for the game are:");

        //sort the scores
        BubbleSort(score);


        Console.ReadLine();
    }//End Main()
    //CalculateScores Method
    //Calculates the average score of an array of integers
    //Takes an array of integers as parameters
    //Returns void
    //Outputs the average to the console
    static void CalculateScores(int[] score)
    {
        int sum = 0;
        int average = 0;
        for (int i = 0; i < score.Length; i++)
        {
            sum += score[i];
            average = sum / score.Length;
        }
        Console.WriteLine("The average score was {0}", average);
    }//End calculateScores

    //Swap method
    //Takes 2 integers as parameters
    //Switches the value of 2 integers (a and b)
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

    //BubbleSort method
    //Sorts an array of integers
    //Takes an array of integers as a parameter
    //Returns void
    //Outputs to the console
    static void BubbleSort(int[] score)
    {

        for (int j = 0; j < score.Length -1; j++)
        {
            for (int i = 0; i < score.Length - 1; i++)
            {
                if (score[i] > score[i + 1])
                {
                    Swap(ref score[i], ref score[i + 1]);
                }
            }
        }
        foreach (int a in score)
            Console.WriteLine("{0}", a);
        Console.ReadLine();
    }
}//End class Program

4 个答案:

答案 0 :(得分:2)

假设names[]score[]对应1对1:

只需采用BubbleSort方法,然后将names[]score[]传递给它

然后,只要您在score[]上执行操作,就可以在names[]上执行此操作。

类似这样的事情

static void BubbleSort(int[] score, string[] names)
{

    for (int j = 0; j < score.Length -1; j++)
    {
        for (int i = 0; i < score.Length - 1; i++)
        {
            if (score[i] > score[i + 1])
            {
                Swap(ref score[i], ref score[i + 1]);
                Swap(ref names[i], ref names[i + 1]);
            }
        }
    }
    foreach (int a in score)
        Console.WriteLine("{0}", a);
    Console.ReadLine();
}

您可能必须为字符串

制作swap方法
static void Swap(ref string a, ref string b)
{
    string temp = a;
    a = b;
    b = temp;
}

答案 1 :(得分:1)

你应该创建一个单独的类来存储玩家的分数数组。

然后制作一系列玩家,您可以根据他们的name

进行排序 编辑:我已将我的答案更新为基于原始代码构建的已实现的播放器类。如果这是针对大学项目的,抄袭检查员可能会看到这一点,所以我会谨慎使用它。

public class Player
{
     public Player(){}
     public Player(string name, int score)
     {
         m_name = name;
         m_score = score;
     }
     public Player(Player p)
     {
         m_name = p.Name;
         m_score = p.Score;
     }
     public string Name
     {
         get{return m_name;}
     }
     public int Score
     {
         get{return m_score;}
     }
     private string m_name
     private int m_score
}

Player[] players = new Player[MAX];
static void BubbleSort(Player[] players)
{

    for (int j = 0; j < players.Length -1; j++)
    {
        for (int i = 0; i < players.Length - 1; i++)
        {
            if (players[i].Score > players[i + 1].Score)
            {
                Swap(ref players[i], ref players[i + 1]);
            }
        }
    }
    foreach (Player a in players)
        Console.WriteLine("{0}", a.Score);
    Console.ReadLine();
}
   static void Swap(ref Player a, ref Player b)
    {
        Player temp = a;
        a = b;
        b = temp;
    }

答案 2 :(得分:0)

不使用两个松散关联值的集合,而是使用类的单个集合:

public class BowlingScore {

  public string Name { get; private set; }
  public int Score { get; private set; }

  public BowlingScore(string name, int score) {
    Name = name;
    Score = score;
  }

}

为集合使用列表而不是数组:

List<BowlingScore> scores = new List<BowlingScore>();

在循环中,您可以创建类的实例并添加到列表中:

BowlingScore item = new BowlingScore(separateInput[0], int.Parse(separateInput[1]);
scores.Add(item);

通过使用列表而不是数组,它只包含您实际添加的项目。您当前的代码需要另一个变量来跟踪数组中实际使用的项目数,以便您不包括最后留空的项目。

现在,由于您将名称和分数作为一个单元,您可以使用与排序数组相同的方法对列表进行排序,只需比较对象的属性。当您交换整个对象时,在对分数进行排序时,名称将跟随分数,反之亦然。

列表中的项目可以使用索引访问,就像数组一样,只有列表的长度在Count属性而不是Length

答案 3 :(得分:0)

无需创建两个数组,因为您正在失去玩家姓名与其分数之间的语义含义。但也没有必要为此创建一个新类。您可以重复使用内置类/结构,如Tuple&lt; ...&gt;或KeyValuePair&lt; ...&gt;。对于排序,您可以使用linq-extension方法。

static void Main(string[] args)
{
    // just some sample players
    const string player1 = "David 100";
    const string player2 = "Jennifer 1430";
    const string player3 = "Eve 234";

    // the string-array with information about players
    var players = new[] { player1, player2, player3 };

    // initialize the array: a tuple is the name of the player and the score
    var scores = new List<Tuple<string, int>>(players.Length);

    foreach (string player in players)
    {
        // split by whitespace
        string[] info = player.Split(' ');

        // be failure tolerant: split must result in at least 2 entries and second one must be integer
        int score;
        if (info.Length <= 2 && int.TryParse(info[1], out score))
            scores.Add(new Tuple<string, int>(info[0], score));
    }

    // print average score
    Console.WriteLine("Average score for {0} players is: {1}{2}", scores.Count, scores.Select(t => t.Item2).Average(), Environment.NewLine);

    // print score of each single player (ordered from highest to lowest score)
    foreach (Tuple<string, int> score in scores.OrderByDescending(t=>t.Item2))
        Console.WriteLine("Player '{0}' => score: {1}", score.Item1, score.Item2);

    Console.WriteLine();
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
}