namespace himiC_sharp
{
class Program
{
static void Main(string[] args)
{
int x;
do
{
Console.WriteLine("WELCOME TO THE SHOPPING CART!\nFollowing options are available to you:\n1. Add an item to cart\n2. Remove an item from the cart\n3. View the cart\n4. Checkout and Pay\n5. Exit");
Console.WriteLine("please inter your chice");
x = Console.Read();
if (x == '1')
{
Console.WriteLine("Available items are:\n1.shirt\n2.pant\n3.shoes\n4.fish\n5.oil");
Console.WriteLine("please inter the items name:");
string j = Console.ReadLine();
}
} while (x != '5');
}
}
}
但是当我希望接受像----
这样的输入时,程序不接受输入但它在获取输入的状态下重复我的console.writeline()方法
答案 0 :(得分:2)
您的代码失败,因为Console.Read只读取输入流中的下一个字符
我想你按1然后按回车键。 char 1由Console.Read
读取,但换行符仍在缓冲区中
当您的代码到达用户应该输入项目的Console.Readline
时,ReadLine会在输入缓冲区中找到换行符并立即退出。
只需将您的Console.Read更改为Console.ReadLine,当然更改接收输入的变量的类型
string menuChoice;
do
{
Console.WriteLine("WELCOME TO THE SHOPPING CART!\nFollowing options are available to you:\n1. Add an item to cart\n2. Remove an item from the cart\n3. View the cart\n4. Checkout and Pay\n5. Exit");
Console.WriteLine("please inter your chice");
menuChoice = Console.ReadLine();
if (menuChoice == "1")
{
Console.WriteLine("Available items are:\n1.shirt\n2.pant\n3.shoes\n4.fish\n5.oil");
Console.WriteLine("please inter the items name:");
string j = Console.ReadLine();
}
} while (menuChoice != "5");
答案 1 :(得分:0)
尝试将ReadLine的输入解析为int:
int choice;
do
{
Console.WriteLine("WELCOME TO THE SHOPPING CART!\nFollowing options are available to you:\n1. Add an item to cart\n2. Remove an item from the cart\n3. View the cart\n4. Checkout and Pay\n5. Exit");
Console.WriteLine("please inter your chice");
choice = Int32.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine("Available items are:\n1.shirt\n2.pant\n3.shoes\n4.fish\n5.oil");
Console.WriteLine("please inter the items name:");
string j = Console.ReadLine();
}
} while (choice != 5);
答案 2 :(得分:0)
尝试使用ReadLine()并将输入转换为int,以便在if()
x = Convert.ToInt32(Console.ReadLine());