ここに学生がいます。ユーザー入力(C#)に基づいて配列の中で最高の値を探しています
現在、ユーザーの入力に基づいて配列の中で最高の値を見つけるためにプロジェクトに取り組んでいます。
私が使用している現在のforeachループは、ユーザーの入力を受け取り、2番目の配列で一致する最初のインスタンスのみを検索します。
私は2つの方法を試しました。どちらも同じ結果に終わります。
まず、リストを作成してソートして元に戻そうとしました。そのように私は0のインデックスを取ることができ、それが最高
static void Main(string[] args)
{
string[] fishColors = new string[15] { "pink", "purple", "red", "orange", "blue", "green", "pink", "green", "blue", "red", "orange", "purple", "green", "red", "purple" };
int[] fishLengths = new int[15] { 49, 5, 45, 10, 14, 1, 44, 17, 48, 11, 13, 17, 20, 15, 37 };
List<int> userFishLengths = new List<int>();
int userChoice = 0;
string input = null;
int longestFish = 0;
do {
Console.WriteLine("Please select the number from the list below for the color of fish you would like to choose:\r\n0. Pink\r\n1. Purple\r\n2. Red\r\n3. Orange\r\n4. Blue\r\n5. Green");
input = Console.ReadLine();
} while (Int32.TryParse(input, out userChoice) == false) ;
string userColor = fishColors[userChoice];
foreach (string fish in fishColors)
{
if (userColor == fish)
{
int indexID = Array.IndexOf(fishColors, fish);
int fishLength = fishLengths[indexID];
userFishLengths.Add(fishLength);
}
}
userFishLengths.Sort();
userFishLengths.Reverse();
Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + userFishLengths[0]+" inches.");
}
は第二になり、私は毎回、それを取り、それは大きなだ場合は、変数を上書き値を作成しようとしました。
static void Main(string[] args)
{
string[] fishColors = new string[15] { "pink", "purple", "red", "orange", "blue", "green", "pink", "green", "blue", "red", "orange", "purple", "green", "red", "purple" };
int[] fishLengths = new int[15] { 49, 5, 45, 10, 14, 1, 44, 17, 48, 11, 13, 17, 20, 15, 37 };
int userChoice = 0;
string input = null;
int longestFish = 0;
do {
Console.WriteLine("Please select the number from the list below for the color of fish you would like to choose:\r\n0. Pink\r\n1. Purple\r\n2. Red\r\n3. Orange\r\n4. Blue\r\n5. Green");
input = Console.ReadLine();
} while (Int32.TryParse(input, out userChoice) == false) ;
string userColor = fishColors[userChoice];
foreach (string fish in fishColors)
{
if (userColor == fish)
{
int indexID = Array.IndexOf(fishColors, fish);
int fishLength = fishLengths[indexID];
if (fishLength > longestFish)
{
longestFish = fishLength;
}
}
}
Console.WriteLine("The longest fish in the tank with the color you chose (" + userColor + ") is " + longestFish + " inches.");
}
ご協力いただきありがとうございます。ありがとうございました!
のために設計されているユーザーが色を選択することになっている、とプログラムが長さで応答していることでしょうか? –
修正プログラムは、ユーザーが選択した色の最大長で応答します。 –
ああ、私はダニエルメイズの答えに行くだろう。色を一意の識別子にする必要がある場合は、それらをキーとしたディクショナリと値としての対応する長さ配列を使用するのが最適な方法です。 –