gpt4 book ai didi

Java时钟程序

转载 作者:行者123 更新时间:2023-12-01 07:46:53 26 4
gpt4 key购买 nike

我正在尝试使用Java制作一个时钟程序,除了无法让程序将负值更改为0之外,我一切正常。我也无法让程序设置小时、分钟的值,如果超出范围,则秒为 0。我有一个必须使用的测试程序,但我的代码中的 T1 和 T2 时钟值不正确。 T1 应为 0:0:0,T2 也应为 0:0:0。但是,当我输出代码时,T1 为 -3:-21:-30,T2 为 24:60:60。我知道我的代码有问题,但我找不到问题,如果有人能够帮助我,我将不胜感激。下面是我的代码,第二部分是我必须使用的测试器代码。

 public class Clock
{
// instance variables
private int hours;
private int minutes;
private int seconds;

public void setHours(int newHours) {
hours = newHours;
if (hours<0 || hours > 24) {
hours = 0;
}
}
public void setMinutes(int newMinutes) {
minutes = newMinutes;
if (minutes<0 || minutes > 60) {
minutes = 0;
}
}
public void setSeconds(int newSeconds) {
seconds = newSeconds;
if(seconds<0 || seconds > 60) {
seconds = 0;
}
}

/**
* Constructor for objects of class Clock
*/
public Clock(int newHour, int newMinute, int newSecond)
{
if (newHour > -1 || newHour < 24) {
this.hours = newHour;
}
else {
setHours(hours);
}
if (newMinute > -1 || newMinute < 60) {
this.minutes = newMinute;
}
else {
setMinutes(minutes);
}
if (newSecond > -1 || newSecond < 60) {
this.seconds = newSecond;
}
else {
setSeconds(seconds);
}
}

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

public String toString() {
return hours + ":"+minutes+":"+seconds;
}

public void tick() {
seconds = seconds +1;
if(seconds >= 60)
{
minutes ++;
seconds = 0;
}
if(minutes >= 60)
{
hours++;
minutes = 0;
}
if(hours >=24)
{
hours = 0;
}

}

}下一部分是测试器代码。

      public class ClockTest {
public static void main(String [] args){

//Create some clocks and print their times
Clock c1 = new Clock(-3,-21,-30);
System.out.println("T1: "+ c1);

c1 = new Clock(24,60,60);
System.out.println("T2: "+ c1);

c1 = new Clock(3,21,30);
System.out.println("T3: "+ c1);

//Tick the clock twice and print its time
c1.tick();
c1.tick();
System.out.println("T4: "+ c1);

c1 = new Clock(3,30,59);
c1.tick();
System.out.println("T5: "+ c1);

c1 = new Clock(3,59,59);
c1.tick();
System.out.println("T6: "+ c1);

c1 = new Clock(23,59,59);
c1.tick();
System.out.println("T7: "+ c1);

c1 = new Clock(0,0,1);
c1.tick();
System.out.println("T8: "+ c1);

c1 = new Clock(1,1,1);
c1.setHours(22);
c1.setMinutes(30);
c1.setSeconds(35);
System.out.println("T9: "+ c1);
System.out.println("T10: " + c1.getHours() + ":"
+c1.getMinutes() + ":" + c1.getSeconds());
}

}

最佳答案

你的条件是错误的。当你写下这个:

if (newHour > -1 || newHour < 24) {

你的真正意思是:

if (newHour > -1 && newHour < 24) {

关于Java时钟程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50012398/

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