我有一个问题。我和我的朋友在一个程序代码上工作,但他使用bool函数true / false。我很困惑那一个。我想知道是否还有其他选择来获取输入以使代码更清晰。请为此提供解决方案 感谢。
static bool needToGetInputFromUser;
static bool isUserEnteredValidInputData = false;
static void Main(string[] args)
{
int Choice;
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please select any of the following options to continue");
Console.WriteLine("");
Console.WriteLine("Press1: To Track Customer ");
Console.WriteLine("Press2 : To track Supplier");
Choice = Convert.ToInt16(Console.ReadLine());
if (Choice == 1)
{
TrackCustomerData();
Console.WriteLine("Would you like to track Supplier? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
TrackSupplierData();
}
}
else if (Choice == 2)
{
TrackSupplierData();
Console.WriteLine("Would you like to track customer? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
TrackCustomerData();
}
}
else
{
Console.WriteLine("Please choose correct choice");
Console.WriteLine("Would you like to re-enter choice? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
needToGetInputFromUser = true;
}
}
} while (needToGetInputFromUser);
答案 0 :(得分:0)
当涉及动态读取输入时,这将是最简单的一个。但是,您也可以使用Form(也是一种简单的方法)或WebPage来相应地读取和调用该方法。在这种情况下,您必须增加代码的复杂性。
步骤:
答案 1 :(得分:0)
只是一个想法
bool GetInput(){
Console.WriteLine("");
if( Convert.ToString(Console.ReadLine()).ToLower() == "y")
return true;
else
return false;
}
我不是一个控制台应用程序的人,任何人都可以编辑这个
答案 2 :(得分:0)
do while是保持控制台重复直到获得所需输入的好方法。将以下代码复制到LinqPad中进行试用,并在不弄乱组代码的情况下进行调整。它以你想要的方式流动。
void Main()
{
var needToGetInputFromUser = false;
var isUserEnteredValidInputData = false;
var choice = 0;
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please select any of the following options to continue");
Console.WriteLine();
Console.WriteLine("Press 1 : To Track Customer ");
Console.WriteLine("Press 2 : To track Supplier");
//previous implementation could throw an exception and end program
//use this for non integer inputs
if (!int.TryParse(Console.ReadLine(), out choice))
{
needToGetInputFromUser = InvalidInput();
}
if (choice == 1)
{
TrackCustomerData();
Console.WriteLine("Would you like to track Supplier? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
TrackSupplierData();
}
}
else if (choice == 2)
{
TrackSupplierData();
Console.WriteLine("Would you like to track Customer? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
TrackCustomerData();
}
}
else
{
//Integers that are not 1 or 2
needToGetInputFromUser = InvalidInput();
}
} while (needToGetInputFromUser);
}
public bool InvalidInput()
{
Console.WriteLine("Please choose correct choice");
Console.WriteLine("Would you like to re-enter choice? (Y/N).");
if (Convert.ToString(Console.ReadLine()).ToLower() == "y")
{
return true;
}
return false;
}
public void TrackCustomerData()
{
//Some customer data work
Console.WriteLine("Customer tracked...");
}
public void TrackSupplierData()
{
//come supllier data work
Console.WriteLine("Supplier tracked...");
}