如何在特定情况下在数组中找到值?

时间:2017-04-02 23:09:48

标签: c# arrays

我正在创建一个数组,该数组存储来自同一行的名称和保龄球分数,然后使用Split()将名称和分数分成两个单独的数组。然后我需要找到最高得分以及得分最高的名称,并使用某种方法将其写入控制台。

这是我到目前为止所拥有的。感谢。

    const int SIZE = 10;

    string[] arrayNames = new string[SIZE];
    int[] arrayScores = new int[SIZE];

    for (int i = 0; i < SIZE; i++){
        Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

        string input = ReadLine();

        if (input == ""){
            break;
        }
        string[] scoreInfo = input.Split();
        arrayNames[i] = scoreInfo[0];

        bool valid = false;
        do{
            if (input == ""){
                break;
            }
            valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
            valid = valid && (arrayScores[i] <= 300);

        } while (!valid);

    }

    int max = bowling.CalcHighest(arrayScores);
    int min = bowling.CalcLowest(arrayScores);
    int average = bowling.CalcAverage(arrayScores);

2 个答案:

答案 0 :(得分:1)

您的问题是您没有在名称和分数之间保持参考。

当您在一行中阅读时,您将值分为arrayNames[i]arrayScores[i]

考虑使用Dictionary而不是两个单独的数组。

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add(name, score);

然后使用字典作为参数而不是数组进行计算。如果您正在使用System.Linq,您可以轻松地对字典进行所有计算:

var orderedDict = dict.OrderByDescending(d => d.Value); //This orders the dictionary by the scor
var first = orderedDict.First(); //This gets the highest score
var last = orderedDict.Last(); //This gets the lowest score
var average = dict.Sum(s => s.Value)/dict.Count(); //This is the average

var firstName = first.Key; //Name of winner
var lastName = last.Key; //Name of loser

答案 1 :(得分:0)

在你的for循环中,你已经获得了最高分,你只需要跟踪它。 arrayScores[i]

这就是我要做的事情:

const int SIZE = 10;

string[] arrayNames = new string[SIZE];
int[] arrayScores = new int[SIZE];

int highScore = 0;
string winner = "";

for (int i = 0; i < SIZE; i++){
    Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

    string input = ReadLine();

    if (input == ""){
        break;
    }
    string[] scoreInfo = input.Split();
    arrayNames[i] = scoreInfo[0];

    bool valid = false;
    do{
        if (input == ""){
            break;
        }
        valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
        valid = valid && (arrayScores[i] <= 300);

        if(valid && arrayScores[i] > highScore){
            highScore = arrayScores[i];
            winner = arrayNames[i];
        }

    } while (!valid);

}

然后在完成for循环后抓住胜利者和highScore。