我试图编写一个程序来显示一个显示分钟和秒的倒数计时器。我知道如何在几秒钟内完成,但我不确定如何在几分钟和几秒钟内完成倒计时。
例如,倒计时应如下所示:
2分59秒
2分58秒
2分57秒
等等
到目前为止,这是我的代码:
import java.util.Scanner;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Scanner scan = new Scanner(System.in);
System.out.println("How much time (In Minutes) ?");
int timet= scan.nextInt();
long delay = timet * 1000;
do
{
Thread.sleep(1000);
System.out.println(timet / 1);
timet = timet - 1;
delay = delay - 1000;
}
while (delay != 0);
System.out.println("Time's Up!");
}
}
答案 0 :(得分:1)
首先,您需要将timet乘以60以将分钟转换为秒(在下面更新)。您可以使用modulo(%)来获取剩余的秒数。请参阅我在“do”中添加的3行,按照您的描述以分钟和秒打印时间。我没有批评其余的代码。
import java.util.Scanner;
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Scanner scan = new Scanner(System.in);
System.out.println("How much time (In Minutes) ?");
int timet= scan.nextInt() * 60; // Convert to seconds
long delay = timet * 1000;
do
{
int minutes = timet / 60;
int seconds = timet % 60;
System.out.println(minutes +" minute(s), " + seconds + " second(s)");
Thread.sleep(1000);
timet = timet - 1;
delay = delay - 1000;
}
while (delay != 0);
System.out.println("Time's Up!");
}
}
示例输出:
How much time (In Minutes) ? 5 5 minute(s), 0 second(s) 4 minute(s), 59 second(s) 4 minute(s), 58 second(s) 4 minute(s), 57 second(s)
答案 1 :(得分:0)
如果我理解你的问题,你应该首先考虑如何格式化几秒钟(我会使用类似的东西),
private static String formatSeconds(long seconds) {
return (seconds != 1) ? String.format(
"%d seconds", seconds) : "1 second";
}
然后,您可以如何格式化分钟/分钟部分 -
static String formatTime(long millis) {
long seconds = millis / 1000;
if (seconds > 60) {
long minutes = seconds / 60;
seconds -= (minutes * 60);
if (minutes > 1) {
return String.format("%d minutes, %s",
minutes, formatSeconds(seconds));
} else {
return String.format("1 minute, %s",
formatSeconds(seconds));
}
}
return formatSeconds(seconds);
}
最后,将它们组合在一起记录开始时的系统时间并计算应该何时结束,然后当前的倒计时时间是结束时间和当前时间之间的差异 - 也就是说,
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("How much time (In Minutes) ?");
int minutes = scan.nextInt();
long startTime = System.currentTimeMillis();
long endTime = startTime + (minutes * 60 * 1000);
while (System.currentTimeMillis() < endTime) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(formatTime(endTime
- System.currentTimeMillis()));
}
System.out.println("Time's Up!");
}