我正在尝试编写一个迷你测验,我希望“再试一次”按钮遵循与“其他”之前的“if”语句相同的规则 using System;public class Program{ public static void Main() { int x; x = int.Parse(Console.ReadLine()); Co
using System;
public class Program
{
public static void Main()
{
int x;
x = int.Parse(Console.ReadLine());
Console.WriteLine("Find a number that can be divided by both 7 and 12");
if ((x % 7 == 0) && (x % 12 == 0))
{
Console.WriteLine("well done, " +x+ " can be divided by 7 and 12");
}
else
{
Console.WriteLine("Wrong, try again.");
Console.ReadLine();
}
}
}
我希望else语句之后的ReadLine遵循与之前的“if”语句相同的规则,但它需要一个全新的语句,并且复制粘贴语句似乎是一个低效的解决方案.
通常,这种处理是在while循环中完成的,循环继续循环直到用户正确回答.因此关键是创建一个条件,当有正确答案时,该条件将变为false.请注意,我们还将x变量重新分配给else块中的Console.ReadLine()方法,否则我们总是比较x的旧值,循环永远不会结束.
例如:
bool answeredCorrectly = false;
while (!answeredCorrectly)
{
if ((x % 7 == 0) && (x % 12 == 0))
{
Console.WriteLine("well done, " + x + " can be divided by 7 and 12");
answeredCorrectly = true; // This will have us exit the while loop
}
else
{
Console.WriteLine("Wrong, try again.");
x = int.Parse(Console.ReadLine());
}
}
如果你想对它真的很棘手,你可以编写一个方法来获取用户的整数,并且它接受可用于验证输入是否正确的函数(任何接受int的方法并返回一个布尔).
这样,您可以创建验证方法并将其(以及用户的提示)传递给从用户获取整数的方法.
请注意,我们使用int.TryParse方法尝试从字符串输入中获取整数.这个方法非常方便,因为它做了两件事:首先,如果解析成功则返回true,第二,它返回out参数中的int值.这样我们就可以使用返回值来确保它们输入一个数字,我们可以使用输出参数来查看数字是否符合我们的条件:
private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
int result = 0;
bool answeredCorrectly = false;
while (!answeredCorrectly)
{
// Show message to user
Console.Write(prompt);
// Set to true only if int.TryParse succeeds and the validator returns true
answeredCorrectly = int.TryParse(Console.ReadLine(), out result) &&
(validator == null || validator.Invoke(result));
if (!answeredCorrectly) Console.WriteLine("Incorrect, please try again");
}
return result;
}
有了这个方法,我们现在可以随意使用我们的main方法调用它,无论我们喜欢什么样的验证,我们不需要每次都重写所有的循环代码:
int x = GetIntFromUser("Enter a number that can be divided by both 7 and 12: ",
i => i % 7 == 0 && i % 12 == 0);
x = GetIntFromUser("Enter a negative number: ", i => i < 0);
x = GetIntFromUser("Enter a number between 10 and 20: ", i => i > 10 && i < 20);
您甚至可以使用它来创建一个只需几行代码的数字猜谜游戏!
int randomNumber = new Random().Next(1, 101);
int x = GetIntFromUser("I'm thinking of a number from 1 to 100. Try to guess it: ", i =>
{
Console.WriteLine(i < randomNumber
? $"{i} is too low - guess a larger number."
: i > randomNumber ? $"{i} is too high - guess a smaller number." : "Correct!");
return i == randomNumber;
});
