C# 使用数组提示用户输入并显示用户输出
我需要帮助。我需要提示用户输入一个介于0和9之间的索引。如果用户输入数组之外的内容,那么我需要使用If语句或try catch来告诉用户不存在这样的分数。这就是我目前所拥有的C# 使用数组提示用户输入并显示用户输出,c#,visual-studio-2013,C#,Visual Studio 2013,我需要帮助。我需要提示用户输入一个介于0和9之间的索引。如果用户输入数组之外的内容,那么我需要使用If语句或try catch来告诉用户不存在这样的分数。这就是我目前所拥有的 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
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
试试这个
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");
}
灵活的解决办法是:
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");
}
程序仍将按预期运行,无需进一步更改。非常简单-
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());
}
}
}`
不使用For循环,而是直接使用contains检查数组中是否存在所需的值。 试试这个
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");
}
'如果用户输入数组之外的内容,那么我需要使用If语句或try catch告诉用户不存在这样的分数。'您尝试过这两种方法吗?国际单项体育联合会是前进的道路。什么阻止了你?谢谢大家。我想得太多了,好吧。我是新来的
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");
}