Я бы попробовал что-то вроде:
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);
//...
Если ваши минимальные и максимальные значения фиксированы, вы не можете передавать их в качестве аргументов и использовать фиксированную проверку. И вы также можете избежать передачи запроса : $
, если это необходимо, но я оставлю это на ваше усмотрение.
Обновлять
Причина, по которой строка 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