gpt4 book ai didi

秒表/计时器的 Java 控制台代码?

转载 作者:行者123 更新时间:2023-11-29 08:17:32 26 4
gpt4 key购买 nike

我这里有秒表所需的代码。我想要的只是摆脱这里的 Swing 部分并在控制台中显示相同的输出。有人可以帮忙吗?

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class ElapsedTime extends JFrame
{
JLabel time;

long startTime = System.currentTimeMillis();

ElapsedTime()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;

String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));

if (seconds.length() < 2)
seconds = "0" + seconds;

if (minutes.length() < 2)
minutes = "0" + minutes;

if (hours.length() < 2)
hours = "0" + hours;

return minutes+":"+seconds;
}

public static void main(String[] args)
{
JFrame obj = new ElapsedTime();
obj.setVisible(true);
}
}

最佳答案

关键是:

a.) 查找要写入控制台的字符以删除最近写入的字符(\b 或 ASCII 中的 \010)
b.) 意识到你需要记住上次更新控制台时你写入了多少个字符
c.) 记住使用 print 而不是 println

public class Test {

public static void main(String[] args) throws InterruptedException {
int charsWritten = 0;
long start = System.currentTimeMillis();
while (1 > 0) {
Thread.sleep(1000);
long elapsedTime = System.currentTimeMillis() - start;
elapsedTime = elapsedTime / 1000;

String seconds = Integer.toString((int) (elapsedTime % 60));
String minutes = Integer.toString((int) ((elapsedTime % 3600) / 60));
String hours = Integer.toString((int) (elapsedTime / 3600));

if (seconds.length() < 2) {
seconds = "0" + seconds;
}

if (minutes.length() < 2) {
minutes = "0" + minutes;
}

if (hours.length() < 2) {
hours = "0" + hours;
}

String writeThis = hours + ":" + minutes + ":" + seconds;

for (int i = 0; i < charsWritten; i++) {
System.out.print("\b");
}
System.out.print(writeThis);
charsWritten = writeThis.length();
}
}
}

注意:您可以通过仅清除控制台以仅显示您正在更改的字符来提高效率,但我认为您不会获得那么多的速度提升。

关于秒表/计时器的 Java 控制台代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491027/

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