MOOC Java 练习 78,有界计数器不接受用户输入



尝试和我的儿子一起学习Java。我已经用谷歌搜索了每个单词组合,但似乎找不到答案。我将不胜感激任何帮助或指导。

程序在分钟/小时内不接收用户输入以启动计数器。因此,计数器从 00:00:50 开始输入 23:59:50。这是我迄今为止的代码:

主类:

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    BoundedCounter seconds = new BoundedCounter(59);
    BoundedCounter minutes = new BoundedCounter(59);
    BoundedCounter hours = new BoundedCounter(23);
    System.out.print("seconds: ");
    int s = Integer.parseInt(reader.nextLine());
    System.out.print("minutes: ");
    int m = Integer.parseInt(reader.nextLine());
    System.out.print("hours: ");
    int h = Integer.parseInt(reader.nextLine());
    seconds.setValue(s);
    minutes.setValue(m);
    hours.setValue(h);

    int i = 0;
    while ( i < 121 ) {
        System.out.println( hours + ":" + minutes + ":" + seconds);   
        seconds.next();
        if(seconds.getValue()== 0){
        minutes.next();
        }
        // if minutes become zero, advance hours
        if(minutes.getValue()== 0 && seconds.getValue()== 0){
            hours.next();
        }
        i++;
    }

}
}
public class BoundedCounter {
    private int value;
    private int upperLimit;
 public BoundedCounter(int upperLimit){
     this.value = 0;
     this.upperLimit = upperLimit;
 }
 public void next(){
    if(value < upperLimit){
        value++;
    }
    else {
        this.value = 0;
    }
    }
 public String toString(){
     if(value < 10){
         return "0" + this.value;
     }
     else{
     return "" + this.value;
}
}
 public int getValue(){
     return this.value;
 }
 public void setValue(int newValue){
     if(newValue > 0 && newValue < this.upperLimit){
         this.value = newValue;
     }
 }
}

两个建议。

将 while 等替换为 for (int i = 0; i <121; i++(。您的方法有效,但使用 for 是更常见的方法。

您可以以不同的方式键入输入,一行是秒,下一行是分钟,第三行是小时。请注意,您正在以相反的顺序读取值。这应该使你现有的代码工作。

或者,看看 API。 useDelimiter(( 采用一个设置分隔符的正则表达式。在您的情况下,":"应该有效。然后,使用 nextInt((。当然,如果您输入错误,这将引发异常。

祝你好运!

BoundedCounter 类中的 setValue 方法只是使您的值略有偏差。您的 setValue 方法应为>= 和 <=:

public void setValue(int newValue){
 if(newValue >= 0 && newValue <= this.upperLimit){
     this.value = newValue;
 }}

最新更新