Я новичок в этом и строил простую программу часов/таймера. Это было очень просто с методами установки времени, получения времени и запуска часов. Все работает, даже таймер. Единственная проблема заключается в том, что при первом запуске таймер выдает сообщение об ошибке:
«Исключение в потоке «основной» java.lang.IllegalStateException: задача уже> запланирована или отменена в java.util.Timer.sched (Timer.java: 401) в java.util.Timer.scheduleAtFixedRate (Timer.java: 328) в Clock.start(Clock.java:53) at ClockTest.main(ClockTest.java:46) Время: 5:55:45 Время: 5:55:46 Время: 5:55:47 Время 5:55:48 Время: 5:55:49 Время: 5:55:50 Время: 5:55:51"
Насколько я понимаю, это означает, что уже запущен еще один таймер, но я не вижу, где он находится в моем коде. Чтобы уточнить, эта ошибка выдается, когда я запускаю таймер, но затем таймер работает.
Вот мой код. Вот основной метод:
import java.util.Scanner;
public class ClockTest{
public static void main (String [] args){
int userInput, hr, min, sec;
Clock clock = new Clock();
Scanner scan = new Scanner(System.in);
System.out.println("What would you like to do?\n1) Set Clock"
+ "\n2) Get the time the clock is set to \n3) Start the timer\n"
+ "4) Exit");
userInput=scan.nextInt();
while (userInput!=4){
if (userInput==1){
System.out.println("Enter the hour: ");
hr=scan.nextInt();
System.out.println("Enter the minutes: ");
min=scan.nextInt();
System.out.println("Enter the seconds: ");
sec=scan.nextInt();
clock.setTime(hr,min,sec);
System.out.println("What would you like to do?\n1) Set Clock"
+ "\n2) Get the time the clock is set to \n3) Start the timer\n"
+ "4) Exit");
userInput=scan.nextInt();
}if(userInput==2){
System.out.println(clock.getTime());
System.out.println("What would you like to do?\n1) Set Clock"
+ "\n2) Get the time the clock is set to \n3) Start the timer\n"
+ "4) Exit");
userInput=scan.nextInt();
}if(userInput==3)
clock.start();
}
}
}
А вот класс Clock, который я создал:
import java.util.Timer;
import java.util.TimerTask;
public class Clock {
int seconds=0;
int hours=0;
int minutes=0;
TimerTask hourTask = new TimerTask(){
public void run() {
seconds++;
if(seconds==60 && minutes!=60 && hours!=60){
seconds=0;
minutes++;
}if(seconds==60 && minutes ==60 && hours!=60){
seconds=0;
minutes=0;
hours++;
}if(seconds==60 && minutes==60 && hours==60){
seconds=0;
minutes=0;
hours=0;
}System.out.println("The time is: " + hours + ":" + minutes + ":" + seconds);
}
};
//---------------------------------------------------------------------
//constructor without parameters
//---------------------------------------------------------------------
public Clock (){
hours=0;
minutes=0;
seconds=0;
}
//---------------------------------------------------------------------
//constructor with parameters
//---------------------------------------------------------------------
public Clock (int hrs, int min, int sec){
hours=hrs;
minutes=min;
seconds=sec;
}
//---------------------------------------------------------------------
//starts the clock
//---------------------------------------------------------------------
public void start(){
Timer hourTimer = new Timer();
hourTimer.scheduleAtFixedRate(hourTask, 1000, 1000);
}
//---------------------------------------------------------------------
//sets the time
//---------------------------------------------------------------------
public void setTime(int hrs, int min, int sec){
hours=hrs;
minutes=min;
seconds=sec;
}
//---------------------------------------------------------------------
//gets the time
//---------------------------------------------------------------------
public String getTime(){
return "The time is: " + hours + ":" + minutes + ":" + seconds;
}
}
Я новичок во всем этом, поэтому, если кто-нибудь может ответить на это, я был бы очень признателен. Кроме того, если вы видите, как я могу улучшить или очистить свой код, я приветствую любую критику.
Кроме того, к вашему сведению, я до сих пор пишу все в TextEdit (моя проф. хорошо учится), так что, если это может выглядеть некрасиво.
Спасибо
seconds
,minutes
иhours
volatile
, поскольку они переназначаются и доступны из разных потоков. - person Titus   schedule 08.04.2016