我必须创建一个函数来返回所选的菜单选项,然后使用switch
语句来显示按下了哪个键,但是我在函数部分遇到了问题。
class Program
{
static void displayMainMenu()
{
string title = "Old Yeller Pet Store";
Console.WriteLine("\n\n");
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth /2) + (title.Length / 2 )) + "}", title));
Console.WriteLine("\n");
title = "Main Menu";
Console.WriteLine("\n\n");
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth /2) + (title.Length / 2 )) + "}", title));
Console.WriteLine("\n");
string line = "1. Buy a Pet";
Console.WriteLine(line.PadLeft(line.Length+1 + 50));
string line2 = "2. Buy Food";
Console.WriteLine(line2.PadLeft(line2.Length+1 + 50));
string line3 = "3. File OPs";
Console.WriteLine(line3.PadLeft(line3.Length+1 + 50));
string line4 = "4. Manager";
Console.WriteLine(line4.PadLeft(line4.Length+1 + 50));
string line5 = "5. Quit";
Console.WriteLine(line5.PadLeft(line5.Length+1 + 50));
}
static void getChoice()
{
Console.WriteLine("Please input which option you choose to use");
}
public static void Main(string[] args)
{
displayMainMenu();
Console.ReadKey();
}
}
}
你应该做的是修改getChoice方法以返回一个字符串,该字符串将是所选的选项。在getChoice方法中编写Console.ReadLine并将值放入变量并返回变量。这样你就可以在displayMenu之后调用函数getChoice并获取值。
我会自己提供代码但是因为这更像是一个功课,我认为你会更好地理解这个并尝试用这个想法自己做:)!
希望这可以帮助!
考虑一下Console.ReadKey()将等到你按一个键继续。在你这样做之后,属性Console.ReadKey()。Key将包含按下的键的值所以,在这种情况下......
var key = Console.ReadKey().Key;
switch (key) {
case ConsoleKey.D1:
Console.WriteLine("You pressed 1");
break;
case ConsoleKey.D2:
Console.WriteLine("You pressed 2");
break;
//etc...//
default:
Console.WriteLine("You pressed something else");
break;
}
所以我觉得这是进步,但我可能错了? Switch语句会替换我的getChoice函数中的If语句吗?
class Program
{
static void displayMainMenu()
{
string title = "Old Yeller Pet Store";
Console.WriteLine("\n\n");
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth /2) + (title.Length / 2 )) + "}", title));
Console.WriteLine("\n");
title = "Main Menu";
Console.WriteLine("\n\n");
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth /2) + (title.Length / 2 )) + "}", title));
Console.WriteLine("\n");
string line = "1. Buy a Pet";
Console.WriteLine(line.PadLeft(line.Length+1 + 50));
string line2 = "2. Buy Food";
Console.WriteLine(line2.PadLeft(line2.Length+1 + 50));
string line3 = "3. File OPs";
Console.WriteLine(line3.PadLeft(line3.Length+1 + 50));
string line4 = "4. Manager";
Console.WriteLine(line4.PadLeft(line4.Length+1 + 50));
string line5 = "5. Quit";
Console.WriteLine(line5.PadLeft(line5.Length+1 + 50));
}
static void getChoice()
{
string option;
int choice;
Console.WriteLine("Please input which number option you choose to use");
option = Console.ReadLine();
choice = Convert.ToInt32(option);
if (choice == 1)
{
Console.Write("Lipsum");
//code to open Buy a Pet menu
}
}
public static void Main(string[] args)
{
displayMainMenu ();
getChoice();
Console.ReadKey();
}
}