我正在尝试编写一个迷你测验,我希望“重试”按钮遵循与“其他”之前的“ if”语句相同的规则
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”语句相同的规则,但是它需要遵循一个全新的语句,并且将其粘贴粘贴似乎是一种低效的解决方案。
答案 0 :(得分:4)
通常,这种处理是在while
循环中完成的,该循环将继续循环直到用户正确回答为止。因此,关键是要创建一个条件,当有正确答案时它将变为false
。
请注意,我们也将x
块中的Console.ReadLine()
变量重新分配给了else
方法,否则我们总是在比较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());
}
}
如果您想真正解决这个问题,可以编写一个方法,该方法将从用户处获取一个整数,并且该函数采用可用于验证输入正确的函数(任何采用{ {1}}并返回int
)。
通过这种方式,您可以创建一个验证方法,并将其(以及针对用户的提示)传递给从用户那里获取整数的方法。
请注意,我们正在使用bool
方法来尝试从字符串输入中获取整数。此方法非常方便,因为它有两件事:首先,如果解析成功,则返回int.TryParse
;其次,它在true
参数中返回int
值。这样,我们可以使用返回值来确保它们输入了数字,并且可以使用输出参数来查看数字是否满足我们的条件:
out
有了这个方法,我们现在可以随时根据需要从主方法调用它,并进行所需的验证,而不必每次都重新编写所有循环代码:
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;
}
您甚至可以只用几行代码就可以用它来创建数字猜谜游戏!
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);
答案 1 :(得分:2)
您是否考虑过在成功的情况下使用while
块和break;
?
using System;
public class Program
{
public static void Main()
{
int x;
Console.WriteLine("Find a number that can be divided by both 7 and 12");
while (true)
{ //Loop the code until it is broken out of
x = int.Parse(Console.ReadLine());
if ((x % 7 == 0) && (x % 12 == 0))
{
Console.WriteLine("well done, " + x + " can be divided by 7 and 12");
Console.ReadKey(); //Pause the program so it doesnt break out immediately
break; //Break out of the while loop
}
else
{
Console.WriteLine("Wrong, try again.");
}
}
}
}