支持我创建"时钟";集合,并将其分钟值更改为1。我已经创建了Clock类(以3 int作为参数(,并将它们放在LinkedList中。但当我试图获取对象的值时,结果是错误的。。。这是我的想法(是的,我知道我必须添加代码,如果分钟超过60,就会改变小时(:
public static void main (String[] args) throws java.lang.Exception{
Random randomizer = new Random();
List <Clock> Clocks = new LinkedList <Clock>();
for (int i=0; i <randomizer.nextInt(9)+1; i++){
Clock clock = new Clock(randomizer.nextInt(24)+, randomizer.nextInt(60), randomizer.nextInt(60));
Clocks.add(clock);
}
for (Clock clock : Clocks) {
clock.checkTime();//this method from Clock class just prints on the console randomized time separated with ":".
clock.set(clock.getHour(), clock.getMinute()+1, clock.getSecond());
}
}
有没有办法只改变这三个int中的一个?
我还考虑创建另一个类";时间";然后使用这个字符串而不是3 int将其转换为字符串和时钟。但我仍然需要代码来从字符串中提取int并更改它们。。。所以我决定不走这条路。
我测试了它(底部的代码(,它工作时没有任何错误。我必须对您的代码进行的唯一更改是从Clock clock = new Clock(randomizer.nextInt(24)+, randomizer.nextInt(60), randomizer.nextInt(60));
中删除+
你能提供更多关于获取对象值错误的信息吗?
至于只更改时钟上的一个数字,您可以向Clock
类添加一个或多个方法来增加值。(例如,获取/设置3个int中的每一个(
...
public void setH(int h) {
this.h = h;
}
public void setM(int m) {
this.m = m;
}
public void setS(int s) {
this.s = s;
}
...
由于您可能只是想增加值,因此可以在Clock
类中执行类似的操作。
...
public void increment(int h, int m, int s) {
this.h += h;
this.m += m;
this.s += s;
}
public void incrementH(){
this.h++;
}
public void incrementM(){
this.m++;
}
public void incrementS(){
this.s++;
}
public void tick() {
/* this.s++;
if (this.s >= 60) {
this.s = 0;
this.m++;
} */
// just the minutes
this.m++;
if (this.m >= 60) {
this.m = 0;
this.h++;
}
}
...
我实现你的代码
import java.util.Random;
import java.util.List;
import java.util.LinkedList;
public class HelloWorld {
public static void main (String[] args) throws java.lang.Exception{
Random randomizer = new Random();
List <Clock> Clocks = new LinkedList <Clock>();
for (int i=0; i <randomizer.nextInt(9)+1; i++){
Clock clock = new Clock(randomizer.nextInt(24), randomizer.nextInt(60), randomizer.nextInt(60));
Clocks.add(clock);
}
for (Clock clock : Clocks) {
clock.checkTime();//this method from Clock class just prints on the console randomized time separated with ":".
clock.set(clock.getHour(), clock.getMinute()+1, clock.getSecond());
}
}
}
class Clock {
private int h, m, s;
public Clock(int h, int m, int s) {
set(h, m, s);
}
public void checkTime() {
System.out.println(h + " " + m + " " + s);
}
public void set(int h, int m, int s) {
this.h = h;
this.m = m;
this.s = s;
}
public int getHour() {
return h;
}
public int getMinute() {
return m;
}
public int getSecond() {
return s;
}
}