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