我想询问用户是否要继续添加两个数字,所以如果他们键入Y
,它将重新启动;如果键入N
,它将退出。
我不确定是应该使用if
/else
还是while
(或两者都使用!(或其他什么。
以下是我目前所拥有的:
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.Write("Do You want to add more numbers? Y / N");
Console.ReadLine();
我怎样才能完成它?
首先,让我们提取方法ReadInt
(为什么要重复自己?(:
private static int ReadInt(string title) {
// keep asking user until correct value provided
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
// If we can parse user input as integer...
if (int.TryParse(Console.ReadLine(), out int result))
return result; // .. we return it
Console.WriteLine("Syntax error. Please, try again");
}
}
主代码:在这里,您可以将代码片段包装到do {...} while
中(因为您希望循环至少执行一次(
do {
int num1 = ReadInt("Enter a number to add: ");
int num2 = ReadInt("Enter another number to add: ");
// (long) num1 - we prevent integer overflow (if num1 and num2 are large)
Console.WriteLine($" {num1} + {num2} = {(long)num1 + num2}");
Console.WriteLine("Do You want to add more numbers? Y / N");
}
while(Console.ReadKey().Key == ConsoleKey.Y);
while (true)
{
Console.Write("Enter a number to add: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number to add: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = num1 + num2;
string num11 = Convert.ToString(num1);
string num22 = Convert.ToString(num2);
Console.WriteLine(" " + num1 + " + " + num2 + " = " + num3);
Console.WriteLine("Do You want to add more numbers? Y / N");
string YesOrNo = Console.ReadLine();
if (YesOrNo == "N")
{
break;
}
}
你需要一个循环,我在这样的场景中看到的最常见的是while循环。然而,您还需要一个break条件,以便while循环结束if语句,这是您可以像上面的示例一样中断的一种方式。如果用户在控制台中输入N,则达到中断。
注意,如果在控制台中键入N以外的任何内容,我的示例将继续运行。