你好,我对C#很新,所以如果我的问题有一个非常明显的答案,请耐心等待。
我正在尝试编写一个代码,向用户显示一个选项数组,并带有一个数字来选择该选项。然后用户选择他们的选项,代码将从数组中显示他们的选择。
所以例如
Select 1 for apples
Select 2 for oranges
Select 3 for pears
Please Enter your Selection :
我一直在键入一个for循环来显示我的区域,但是我无法让我的程序读取数组中的输入这是我到目前为止所拥有的
static void Main(string[] args) {
string[] fruit = [3]
fruit[0]=("apples");
fruit[1]=("oranges");
fruit[2]=("pears");
for (int i = 0; i < fruit.length; i++)
{
Console.WriteLine("Enter {0} to select {1}", i, fruit[i]);
}
string choice = Console.ReadLine();
int i = int.Parse(choice);
Console.WriteLine("You have selected {0} which is {1}", i, fruit[i]);
Console.ReadLine();
}
这给了我一个错误,如果我把它放在for循环中,那么程序不会显示我的所有选项。
答案 0 :(得分:4)
您的代码存在多个问题:
string[] fruit = new string[3];
i
,因此您需要为输入使用新变量。 for
循环中的条件应为i < fruit.Length
int.TryParse
来解析来自控制台的输入,检查输入的数字是否为int
并检查数字是否小于数组长度。 答案 1 :(得分:3)
您需要为循环变量或用户选择指定不同的名称。
此外,您可能希望TryParse
使用Parse
的intead来阻止可能的FormatExceptions
:
int userChoice;
if(int.TryParse(choice, out userChoice) && userChoice < fruit.Length)
Console.WriteLine("You have selected {0} which is {1}", userChoice, fruit[userChoice]);
答案 2 :(得分:2)
void Main()
{
// compile a list of possible fruits (remember that c# arrays are
// 0-indexed (first element is actually 0 and not 1))
string[] fruits = new[]{
"apples",
"oranges",
"pears"
};
// iterate over the options and output each one
for (var i = 0; i < fruits.Length; i++){
// add one to index value to make it non-0 based
Console.WriteLine("Enter {0} to select {1}", i + 1, fruits[i]);
}
// continue to read user input until they select a valid choice
Int32 choice = 0;
do
{
// read user input
String input = Console.ReadLine();
// [try to] convert the input to an integer
// if it fails, you'll end up with choice=0
// which will force the while(...) condition to fail
// and, therefore, retry for another selection.
Int32.TryParse(input, out choice);
}
// number should be between 1 and (fruits.Length + 1)
while (choice < 1 || choice > (fruits.Length + 1));
// to reference it, subtract 1 from user's choice to get back to
// 0-indexed array
Console.WriteLine("You have selected {0} which is {1}", choice, fruits[choice - 1]);
}
答案 3 :(得分:1)
您有多个拼写错误,而且您无法使用变量i
两次。
试试这个:
static public void Main(string[] args)
{
string[] fruit = new string[3];
fruit[0]=("apples");
fruit[1]=("oranges");
fruit[2]=("pears");
for (int i = 0; i < fruit.Length; i++)
{
Console.WriteLine("Enter {0} to select {1}", i, fruit[i]);
}
string choice = Console.ReadLine();
int j = int.Parse(choice);
Console.WriteLine("You have selected {0} which is {1}", j, fruit[j]);
Console.ReadLine();
}
如果用户输入的内容无法解析为int
,您可能还希望包含一些错误捕获(例如,您可以使用TryParse
)。
错别字:您的数组声明错误,并且您需要长度为L
的数组长度属性。
答案 4 :(得分:0)
您的字符串数组声明不正确。尝试
string[] fruit = new string[3];
或者您可以声明并启动:
string[] fruit = new string[3]{"apples", "oranges", "pears"};
或更简单:
string[] fruit = {"apples", "oranges", "pears"};