我需要帮助。我需要提示用户输入介于0和9之间的索引。如果用户输入了数组之外的内容,那么我需要使用" if"声明或"尝试捕获"告诉用户"不存在这样的分数"。这是我到目前为止所做的。
public class Program
{
public static void Main(string[] args)
{
int[] GameScores = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("Please enter an index between 0 and 9");
int gamescores = int.Parse(Console.ReadLine());
for (int i = 0; i < GameScores.Length;i++)
{
GameScores[i] = int.Parse(Console.ReadLine());
}
} // end Main
答案 0 :(得分:0)
试试这个
int[] GameScores = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("Please enter an index between 0 and 9");
int gamescores = int.Parse(Console.ReadLine());
if (gamescores >= 0 && gamescores<=9)
{
for (int i = 0; i < GameScores.Length; i++)
{
GameScores[i] = int.Parse(Console.ReadLine());
}
}
else
{
Console.WriteLine("Number not valid");
}
答案 1 :(得分:0)
灵活的解决方案是:
public static void Main(string[] args)
{
int scoreSize = 10;
int[] gameScores = Enumerable.Range(1, scoreSize).ToArray();
Console.WriteLine("Please enter an index between 0 and {0}", gameScores.Length - 1);
int selectedIndex = Convert.ToInt32(Console.ReadLine());
if(selectedIndex >= 0 && selectedIndex < gameScores.Length)
for(int i = 0; i < gameScores.Length; i++)
gameScores[i] = Convert.ToInt32(Console.ReadLine());
else
Console.WriteLine("No such score exists");
}
这样,如果您将scoreSize
更改为20
,例如。
int scoreSize = 20;
该计划仍将按预期运作,无需进一步更改。
答案 2 :(得分:0)
非常简单 -
public static void Main(string[] args)
{
int[] GameScores = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Console.WriteLine("Please enter an index between 0 and 9");
int gamescores = int.Parse(Console.ReadLine());
if (gamescores < 0 || gamescores > 9)
{
Console.WriteLine("No such score exists");
}
else
{
for (int i = 0; i < GameScores.Length; i++)
{
GameScores[i] = int.Parse(Console.ReadLine());
}
}
}`
答案 3 :(得分:0)
您可以直接使用contains来检查数组中是否存在所需的值,而不是使用For循环。 试试这个。
int[] GameScores = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Console.WriteLine("Please enter an index between 0 and 9");
int gamescores = int.Parse(Console.ReadLine());
if (GameScores.Contains(gamescores))
{
Console.WriteLine("score exists");
}
else
{
Console.WriteLine("No such score exists");
}