整数验证方法
Integer validation method
我在试卷上遇到了这个问题,我遇到了麻烦:
Write the body of code for the method
public static int enter_No_Of_Items(int min, int max)
which will allow the user to enter a value for the number of items bought.
The value should be validated in the range min to max. Your answer should include data declaration, prompt and input statements, range check, error message control.
可能只有我一个人,但这个问题似乎很愚蠢,因为我认为验证会 return 真或假而不是整数,如果有人能帮我回答这个问题或准确解释问题想要什么太好了,我们将不胜感激。
你是对的。一般一个验证:
- returns一个
bool
表示好坏;
- 没有 return 值,如果无效则抛出异常。
但是,在这种情况下,系统会要求您 'ask the user' 输入一个值。您的方法的范围不仅是验证,它也在检索输入。这可能是预期的 return 值。
如果输入的号码无效,您可以抛出异常,或者继续询问,直到他们最终输入有效号码。
我试着写了这个方法,这是我能想到的最好的方法:
public static int enter_No_Of_Items(int min, int max)
{
string input = "input";
bool ok = false;
while (ok == false)
{
Console.WriteLine("Enter a number between {0} and {1}.", min, max);
input = Console.ReadLine();
if ((int.Parse(input) >= min) && (int.Parse(input) <= max))
{
Console.WriteLine("Valid number.");
break;
}
Console.WriteLine("Invalid number.");
}
return int.Parse(input);
}
static void Main(string[] args)
{
int randomA = 5;
int randomB = 9;
int itemCount = enter_No_Of_Items(randomA, randomB);
Console.ReadLine();
}
如果我能得到有关如何改进它的反馈,那就太好了。谢谢
我在试卷上遇到了这个问题,我遇到了麻烦:
Write the body of code for the method
public static int enter_No_Of_Items(int min, int max)
which will allow the user to enter a value for the number of items bought.
The value should be validated in the range min to max. Your answer should include data declaration, prompt and input statements, range check, error message control.
可能只有我一个人,但这个问题似乎很愚蠢,因为我认为验证会 return 真或假而不是整数,如果有人能帮我回答这个问题或准确解释问题想要什么太好了,我们将不胜感激。
你是对的。一般一个验证:
- returns一个
bool
表示好坏; - 没有 return 值,如果无效则抛出异常。
但是,在这种情况下,系统会要求您 'ask the user' 输入一个值。您的方法的范围不仅是验证,它也在检索输入。这可能是预期的 return 值。
如果输入的号码无效,您可以抛出异常,或者继续询问,直到他们最终输入有效号码。
我试着写了这个方法,这是我能想到的最好的方法:
public static int enter_No_Of_Items(int min, int max)
{
string input = "input";
bool ok = false;
while (ok == false)
{
Console.WriteLine("Enter a number between {0} and {1}.", min, max);
input = Console.ReadLine();
if ((int.Parse(input) >= min) && (int.Parse(input) <= max))
{
Console.WriteLine("Valid number.");
break;
}
Console.WriteLine("Invalid number.");
}
return int.Parse(input);
}
static void Main(string[] args)
{
int randomA = 5;
int randomB = 9;
int itemCount = enter_No_Of_Items(randomA, randomB);
Console.ReadLine();
}
如果我能得到有关如何改进它的反馈,那就太好了。谢谢