Бих опитал нещо като:
decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
Console.Write(inputQuery);
decimal val;
while(true)
{
if(!decimal.TryParse(Console.ReadLine(), out val))
Console.Write("Please enter a valid decimal value: $");
else if(val < min || val > max)
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
else // the value is a decimal AND it's correct
break;
}
return val;
}
След това го използвайте като:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
//...
Ако вашите min и max са фиксирани, тогава не можете да ги предадете като аргументи и да използвате фиксирана проверка. Можете също така да избегнете предаването на заявката : $
, ако е необходимо, но ще оставя това на вас
Актуализация
Причината, поради която редът return val
ви дава грешка, е, че го вграждате (вероятно в връщаща функция void
). Това, което правех, беше да направя функция, тъй като вие посочихте, че тя трябва да може да се използва повторно.
Така че във вашата програма трябва да направите отделна функция... вашата програма ще изглежда така:
class Program
{
// We're declaring this function static so you can use it without an instance of the class
// This is a function, so it can be called multiple times, with different arguments
static decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
// Write the argument "inputQuery" to console
Console.Write(inputQuery);
decimal val;
// Loop indefinitely
while(true)
{
// Read from console into a decimal "val"
if(!decimal.TryParse(Console.ReadLine(), out val))
// It was not a correct decimal, so write the prompt
Console.Write("Please enter a valid decimal value: $");
// It was a correct decimal
else if(val < min || val > max)
// But not in range, so write a different prompt
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
// It was a decimal and within range
else
// so we break the infinite loop and exit after the "}"
break;
// If we have got to this point (we didn't hit the "break"),
// it was either not a decimal or it wasn't within range,
// so it'll loop again and ask for a value from console again.
// The prompt was already written above (in the "ifs")
}
// We got out of the while(true){} loop, so it means we hit "break"
// above, and that means "val" contains a correct value (decimal and
// within range), so we return it to the caller
return val;
}
static void Main()
{
// Your original code went here, but see how my function is *outside* function Main()
// You use my function (GetUserInput) here:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
// Then with the returned values (stored in "startingBalance"
// and "endBalance"), you can do what you want:
Console.WriteLine("Starting balance was: " + startingBalance.ToString("n"));
}
}
Направих цигулка с цялата програма, така че можете да тествате онлайн и да правите промени: https://dotnetfiddle.net/HiwwIP
person
Jcl
schedule
20.02.2015
while (!decimal.TryParse(Console.ReadLine(), out balance) || balance < 1 || balance > 1000000)
- person DGibbs   schedule 20.02.2015if
изрази, които саif
в рамките на друг. - person mcy   schedule 20.02.2015