我需要一些帮助将分割数组排序为从最高到最低,同时将名称保持在分数旁边。我有点不确定如何这样做,因为阵列是分裂的。此外,有没有办法让用户输入任意数量的名称和分数,而程序没有给用户一个错误?因此,如果他们只想输入4个名字和分数,他们所要做的只是输入?
这是我到目前为止的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace proj09LEA
{
class Program
{
static void Main(string[] args)
{
// declare and array of integers
string[] name = new string[5];
int[] score = new int[5];
Console.WriteLine("\nSaturday Coder's Bowling Team");
Console.WriteLine("Enter in a name and score for each person on the team.");
Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");
// fill an array with user input
for (int i = 0; i < score.Length; i++)
{
Console.WriteLine("Enter in a name and score: ");
string line = Console.ReadLine();
name[i] = line.Substring(0, line.IndexOf(' '));
score[i] = int.Parse(line.Substring(line.IndexOf(' ') + 1));
}
Console.WriteLine("------------ Input Complete ------------\n");
Console.WriteLine("Here are the scores for this game, from highest to lowest:\n");
for (int i = 0; i < score.Length; i++)
{
if (score[i] >= 300)
{
Console.WriteLine("{0}'s score was {1}*.", name[i], score[i]);
}
else
{
Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
}
}
AverageScore(score);
Console.WriteLine("Press Enter to continue. . .");
Console.ReadLine();
}
static void AverageScore(int[] score)
{
int sum = score.Sum();
int average = sum / score.Length;
Console.WriteLine("The average score for this game was {0:d}.\n", average);
}
}
}
答案 0 :(得分:5)
让我首先解决无限玩家的问题。如你所知,数组的大小在创建时是固定的。但是,有一个数据结构List
,它可以具有无限(实际上)数量的元素。您可以创建一个这样的:
List<string> names = new List<string>();
然后,如果要添加新名称,可以使用
names.Add("Mary");
你的代码的其余部分应该是相同的;索引工作正常,求和工作正常,等等。
现在把它们一起排序怎么样?好吧,你不真的有一个名单和一个分数列表;你在语义上真正拥有的是名单和分数对的列表,或者一组玩家。您可以先定义一个代表玩家的结构:
struct Player {
public string Name { get; set; }
public int Score { get; set; }
public Player(string name, int score) {
Name = name;
Score = score;
}
}
然后你可以得到一个球员名单:
List<Player> players = new List<Player>();
我们不是单独添加名称和分数,而是将它们一起添加:
string name = /* ... */;
int score = /* ... */;
players.Add(new Player(name, score));
这样表示,您的打印程序也变得更简单。你可以一次迭代两个:
foreach(Player player in players) {
Console.WriteLine("{0} scored {1}", player.Name, player.Score);
}
最后,总结有点棘手,但并不太难。基本上,我们提取所有分数并总结:
int sum = players.Select((player) => player.Score).Sum();
但对你来说,真正的好处是终于能够对它进行排序:
players.Sort((x, y) => y.Score - x.Score);
答案 1 :(得分:0)
你基本上需要的是看一下专门用于此目的的HashMaps ADT。其结构如下:
-key1:value1
-key2:value2
.....
-keyn:估价
你的钥匙应该是你的分数(但它可以是任何东西)。该值将是与分数关联的名称
然后,您可以创建一个方法sortKeys,具体取决于您的实现,它将获取HashMap中的每个键,在结尾或开头移动它,同时指向您的名称。
但请注意,一些HashMaps是随机存储的,因此您必须创建一个数组来编写键的排序顺序(然后在HashMap中查找键的值)。
答案 2 :(得分:0)
首先使用Arrays.sort方法对数组进行排序,然后从
循环 for(int i= x.length-1;i>=0;i--)
System.out.print(x[i]+"");
应该这样工作
答案 3 :(得分:0)
列表将是一个更好的选择,它们包含在内置的排序选项中,可以使您的任务更轻松。