用户每次输入新号码时都要写号码

时间:2019-02-01 12:07:25

标签: c#

目前,我有以下方法:

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Please enter magical number");
        string input = "";
        int number = int.Parse(Console.ReadLine());

        if(number > 0){
            for (int i = 1; i <= number; i++)
            {
                Console.Write("{0}, ", i);
            }

            Console.WriteLine("Pick another number");
            input = Console.ReadLine();
        } else {
            Console.WriteLine("Wow that number is too low for me!");
        }
    }
}

第一次运行时,一切都会正常进行,但是当用户输入新数字时,该方法将停止。我该如何预防?我在做什么错了?

2 个答案:

答案 0 :(得分:2)

  

在第一次运行时,一切正常,但是当用户   输入新号码,方法将停止。我该如何预防?

通过使用循环而不是if。您还应该使用int.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解决了最后一个逗号的问题。

答案 1 :(得分:2)

请勿将所有内容放入单个 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);
  }
}