gpt4 book ai didi

C# 如何使重复输入重叠?

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:10 24 4
gpt4 key购买 nike

当输入的类型不是整数时,程序应该会失败。但是,有两个问题:

  1. 在输入一个字母并得到“无效”响应后,如果下一个输入是数字,它不会接受并显示“无效”。
  2. 我怎样才能做到这一点,当输入错误的数字时,它会停留在同一行并且只是从屏幕上清除之前的输入(并允许从相同的位置重试)?

    static void Main(string[] args)
    {
    int firstNum;
    int Operation = 1;

    switch (Operation)
    {
    case 1:
    Console.SetCursorPosition(0, 0);
    Console.Write("Write a number: ");
    firstNum = ReadInteger("");
    Console.ReadKey();
    break;
    }
    }

    private static int ReadInteger(string title)
    {
    while (true)
    {
    if (!string.IsNullOrWhiteSpace(title))
    Console.WriteLine(title);

    string input = Console.ReadLine();

    if (int.TryParse(input, out int result))
    return result;

    Console.WriteLine("Sorry, not a valid integer value; please, try again.");
    Console.ReadKey();
    }
    }

最佳答案

广告 1)

因为 ReadInteger 末尾有 Console.ReadKey,它也会被执行。因此,如果您在 string input = Console.ReadLine(); 行中点击 Console.ReadLine 并输入非数字的内容,int.TryParse 将返回 false。这会导致错误消息和 Console.ReadKey 的执行。所以你应该首先摆脱那里的 Console.ReadKey


广告 2)

您正在之前 ReadInteger 的调用设置光标位置,但不是 ReadInteger 的调用中。因此,如果有人输入文本,输入结束通常是通过按回车键完成的。然后写一行(使用 Console.WriteLine)。因此,如果您想让光标位于同一位置,则必须在 ReadInteger 方法内的循环中重置它的位置。

关于C# 如何使重复输入重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53308356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com