【问题标题】:How to make a timer that outputs on one line [duplicate]如何制作一个在一行上输出的计时器[重复]
【发布时间】:2020-08-19 21:30:28
【问题描述】:

目前我已经制作了一个可以在多行上输出的计时器,如下所示:

但是,如果用户选择 1000 秒会占用太多空间。

我需要一种方法,让它自动将第一行更改为下面的数字。

这是我的计时器代码:

public class TimerExample
{
    static int UserInputs()
    {
        int numberOfSeconds;
        do
        {
            Console.WriteLine("How many seconds would you like the test to be? Please type a number divisible by 10!");
            int.TryParse(Console.ReadLine(), out numberOfSeconds);
        } while (numberOfSeconds % 10 != 0);
        return numberOfSeconds;
    }
    public class TimerClass
        {
            public static int Timers(int timeLeft)
            {
                do
                {
                    Console.WriteLine($"timeLeft: {timeLeft}");
                    timeLeft--;
                    Thread.Sleep(1000);
                } while (timeLeft > 0);
                return timeLeft;
            }
        }
    public static void Main(string[] args)
    {
        int numberOfSeconds = UserInput();
        TimerClass.Timers(numberOfSeconds);
    }
}

如果您需要,这是我的完整代码: https://github.com/CrazyDanyal1414/mathstester

【问题讨论】:

  • 使用Console.Write 代替Console.WriteLine
  • @bradbury9 Console.Write() 如果用户输入 10,将提供诸如 10987654321 的输出

标签: c# timer user-input


【解决方案1】:

如果您希望倒计时显示在同一行,则可以更改以下行

Console.WriteLine($"timeLeft: {timeLeft}");

Console.Write("\rtimeLeft: {0}   ", timeLeft);

希望这对你有用。 \r 将重写同一行

【讨论】:

  • 感谢您的第一个回答。我刚刚将您的代码缩进了 4 个空格以启用语法着色。
  • 你也可以很好地使用:```cs
【解决方案2】:

关键是要使用:

  1. Console.Write 而不是 Console.WirteLine
  2. 在打印开始时使用“\r”,以便覆盖该行而不是将数据附加到该行

这里有一些代码要测试:


for (int i = 0; i < 1000; i++)
{
    Console.Write("\r" + i);
    Thread.Sleep(100);
}

【讨论】:

    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多