Я делаю простую игру на Java, и в ней я хочу узнать, сколько времени пользователь тратит, чтобы угадать число, но это говорит мне об этом: локальные переменные, на которые ссылается внутренний класс, должны быть окончательными или эффективно конечными. Спасибозаранее ...
Вот код к игре
//Creating the random number with the user initialized random class
Random rand = new Random();
int n = rand.nextInt(20) + 1;
//Variables are declared
int lives = 10;
int secondsPassed = 0;
//The JOptionPane (Pop-up window) is intitialized
JOptionPane j = new JOptionPane(JOptionPane.INFORMATION_MESSAGE);
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
secondsPassed++;
}
};
while (true){
int num = Integer.parseInt(JOptionPane.showInputDialog(j,"I am thinking of a number between 1 and 20. You have " + lives + " lives. Can you guess it?","EasyMode Singleplayer",JOptionPane.INFORMATION_MESSAGE));
timer.scheduleAtFixedRate(task,1000,1000);
//Here the program decides if the user has lost the game or if he still has lives left
if(lives == 0){
JOptionPane.showMessageDialog(j,"You have lost the game!","EasyMode singleplayer",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}else if(lives > 0){
//The program checks to see if the number is Higher/Lower or equal to the random number generated
if(num == n){
String options[] = {"Yes","No"};
timer.cancel();
timer.purge();
JOptionPane.showMessageDialog(j,"You are correct ! You finished the game with " + lives + " lives!" );
int saving = JOptionPane.showOptionDialog(j,"Do you want to save your score?","Save",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options,options[1]);
//Here the program asks the player if he wants to save his lives to his home directory
if(saving == 0){
try{
String userHomeFolder = System.getProperty("user.home");
File file = new File(userHomeFolder,"Scores.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write("You finished EASYMODE with " + lives + " lives out of 10 lives on Guess The Number!");
writer.write("It only took you " + secondsPassed);
writer.flush();
writer.close();
//bar.add(panel);
JOptionPane.showMessageDialog(j,"File successfully saved to your home directory!","File Saved",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}catch(IOException e){
e.printStackTrace();
}
}else{
System.exit(0);
}