gpt4 book ai didi

java - 自午夜以来的总秒数,Java

转载 作者:行者123 更新时间:2023-12-01 10:02:13 25 4
gpt4 key购买 nike

我对编程真的很陌生。我正在做一项 Java 入门作业。在我的作业中,我们需要找到自午夜以来的总秒数,并将该数字更改为小时、分钟和秒以显示当前时间。我有一个小问题。当我测试我的代码时,总秒数显示 0!任何帮助,将不胜感激。抱歉,代码很困惑

        package clock;
import java.text.DecimalFormat;
import java.util.Calendar; // to get current time

public class Clock {
public static int totalseconds;
public static int seconds;
public static int minutes;
public static int hours;

public static int test;

public Clock(int hours, int minutes, int seconds ) {
setHours(hours);
setMinutes(minutes);
setSeconds(seconds);
}


// use current time
public Clock() {
Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;
totalseconds = (int) secondsPassed;


}


public void tick() {
addSecond();
}

private void addSecond() {
seconds = totalseconds%60;
}

private void addMinute() {
minutes = totalseconds/60 % 60;
}

private void addHour() {
hours = totalseconds / 3600;
}

public String toString() {
DecimalFormat f = new DecimalFormat("00");
return f.format(hours) + ":" + f.format(minutes) + ":" + f.format(seconds);
}

public int getHours() {
return hours;
}
public int getMinutes() {
return minutes;
}
public int getSeconds() {
return seconds;
}

// the total number of minutes sinces midnight
public int getTotalMinutes() {
return totalseconds / 60 % 60;
}

// the total number of seconds since midnight
public int getTotalSeconds() {
return totalseconds;
}

public void setHours(int hours) {
if (hours > 23 || hours < 0) {
this.hours = 0;
}
else
this.hours = hours;
}
public void setMinutes(int minutes) {
if (minutes > 59 || minutes < 0)
this.minutes = 0;
else
this.minutes = minutes;
}
public void setSeconds(int seconds) {
if (seconds > 59 || seconds < 0)
this.seconds = 0;
else
this.seconds = seconds;
}

// reset hours, minutes and seconds to zero
public void reset() {
hours = minutes = seconds = 0;
}
public static void main(String [] args){

System.out.println("this is total seconds " + test + totalseconds );
}


}

最佳答案

将 main 更改为此。

public static void main(String [] args){
Clock clock = new Clock();
System.out.println("this is total seconds " + test + totalseconds );
}

新建一个 Clock 实例并调用构造函数,所有的魔法都在这里发生。

关于java - 自午夜以来的总秒数,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710810/

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