2 回答
TA贡献2012条经验 获得超12个赞
在第一次运行时,一切都按预期工作,但是当用户输入新编号时,方法停止。我该如何防止这种情况?
通过使用循环而不是 .您还应该 使用 来处理无效输入:ifint.TryParse
do
{
Console.WriteLine("Please enter magical number or enter exit to stop");
string enteredNumber = Console.ReadLine()?.Trim();
if ("exit".Equals(enteredNumber, StringComparison.InvariantCultureIgnoreCase))
{
break;
}
bool valid = int.TryParse(enteredNumber, out int number);
while (!valid)
{
Console.WriteLine("Please enter a valid integer");
valid = int.TryParse(Console.ReadLine()?.Trim(), out number);
}
if (number > 0)
{
Console.WriteLine(string.Join(", ", Enumerable.Range(1, number)));
}
else
{
Console.WriteLine("Wow that number is too low for me!");
}
} while (true);
我还通过使用修复了末尾最后一个逗号的问题。string.Join
TA贡献1831条经验 获得超10个赞
不要把所有东西都放到一个单一的,提取方法:Main
private static int? ReadInteger(string title) {
if (string.IsNullOrWhiteSpace(title))
Console.WriteLine("Please, input integer value or \"quit\"");
else
Console.WriteLine($"{title}. Print \"quit\" to exit.");
while (true) {
string value = Console.ReadLine().Trim();
if (string.Equals(value, "quit", StringComparison.OrdinalIgnoreCase))
return null;
else if (int.TryParse(value, out int result))
return result;
Console.WriteLine("Sorry, the format is incorrect. Please, try again.");
}
}
private static void Report(int number) {
Console.WriteLine(number <= 0
? "Wow that number is too low for me!"
: String.Join(", ", Enumerable.Range(1, number)));
}
现在,让我们实现一个简单的方法:Main
public static void Main() {
// Just a simple "for" loop:
// - start with "Please enter magical number"
// - keep on until user puts "quit"
// - ask "Pick another number" for another numbers
for (int? value = ReadInteger("Please enter magical number");
value.HasValue;
value = ReadInteger("Pick another number") {
Report(value.Value);
}
}
- 2 回答
- 0 关注
- 84 浏览
添加回答
举报