0

我被指示编写一个程序,该程序从用户那里收集保龄球得分(整数)和名称,用空格分隔,并使用该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

4 回答 4

2

Assuming that names[] corresponds 1 to 1 with score[]:

Just take your BubbleSort method, and pass both names[] and score[] into it

Then, you whenever you do an operation on score[] do it on names[] too.

something like this

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();
}

you might have to make a swap method for strings

static void Swap(ref string a, ref string b)
{
    string temp = a;
    a = b;
    b = temp;
}
于 2013-03-25T16:12:08.127 回答
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;
    }
于 2013-03-25T16:11:11.403 回答
0

无需创建两个数组,因为您失去了玩家姓名和分数之间的语义含义。但也不需要为此创建一个新类。您可以重用内置类/结构,例如 Tuple<...> 或 KeyValuePair<...>。对于订购,您可以使用 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();
}
于 2013-03-25T17:11:32.790 回答
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.

于 2013-03-25T16:18:17.950 回答