在觸發我的方法並將數據存儲到我的數據庫之前,我需要從控制檯應用程序中檢查一組用戶輸入。在觸發方法之前需要驗證一組用戶輸入c#
該程序編譯和rund沒有例外。但是如果有一個錯誤的輸入,其他三個輸入仍然會通過。
雖然,我真正需要的是在觸發方法之前確保4個用戶的條目是正確的,萬一只有一個錯誤,整個程序應該停止並退出。你可以採用
using System;
using System.Threading;
namespace BarcodeValidation
{
class Program
{
static void Main(string[] args)
{
ReadBarcode();
}
static void ReadBarcode()
{
var barcodes = GetInput();
foreach (var item in barcodes)
{
// something
CheckUserInput(item);
}
}
static string[] GetInput()
{
Console.WriteLine("Please enter 4 products ID, Barcodes, MPN or EAN code:");
string[] barcode = new string[4];
for (int i = 0; i < barcode.Length; i++)
{
barcode[i] = Console.ReadLine();
}
return barcode;
} // end of method here
static void CheckUserInput(string userInput)
{
int msec = 5000;
try
{
if (!(userInput == "F5121" || userInput == "F3111" || userInput == "F8331" || userInput == "F5321"))
{
Console.WriteLine("Enter a valid MPN codes for your products");
Thread.Sleep(msec);
Environment.Exit(0);
}
else
{
switch (userInput)
{
case "F5121":
Console.WriteLine("barcode 1 is =", userInput);
Thread.Sleep(msec);
break;
case "F3111":
Console.WriteLine("barcode 2 is =", userInput);
Thread.Sleep(msec);
break;
case "F8331":
Console.WriteLine("barcode 3 is =", userInput);
Thread.Sleep(msec);
break;
case "F5321":
Console.WriteLine("barcode 4 is =", userInput);
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
這不就是你在做什麼?爲每個項目檢查用戶輸入。如果輸入不正確,則CheckUserInput會退出。您當前的程序中有哪些不起作用? – Default
'bool errorOccurred = false;'=>替換'foreach' w /'while(errorOccurred == false)',並且在輸入無效時將'errorOccurred'設置爲true? 檢查後,再看看是否繼續。 –
你想「不運行」程序的哪一部分?因爲如果至少有一個條目不正確,它會退出程序,您已經擁有該權限。它會立即退出。但是,如果所有4都通過了「CheckUserInput」,那麼程序已經結束了,就像在「ReadBarcode」中發生的那樣......如果它們中的任何一個錯誤,你都不想運行什麼? – Skintkingle