0

How I can stoped or canceled my timertask void ? Because TimerTask void stopped my loop and I don't know how I can resolve my problem.

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;





public class Main {
    public static void main(String [] args) throws Exception {
        int hp = 10;
        Scanner sc = new Scanner(System.in);
        do{
            Random los = new Random();
            int pc = 1 + los.nextInt(6);
            TimerTask zd = new TimerTask(){
                public void run(){
                    System.out.println("Czas off");
                    System.out.println("5 sek");
                                        
                 } 
                         
            };
            Timer czas = new Timer();
            czas.schedule(zd, 5 * 1000);
            System.out.println("5 sek na odp");
           
            String odp = sc.nextLine();
            switch(odp){
                case "atk":
                    System.out.println("oo tak");
                     hp = hp - pc;
                    System.out.println("hp spadlo o " + pc + " "  + " wynosi " + hp);
                                                           
                    break;
                default:
                    System.out.println("zle");
                       
                    hp = hp + pc;
                    System.out.println("hp wzroslo o " + pc);
                       
                }
            
            
           }while(hp>0); 
                      
                System.out.println("pokonany");    
    }
        
}

There is a code, when time out. My loop has stop working and them is starter a void run, but I cant go back to my loop. How I can resolve this?

I'm try using zd.cancel(); But this doesnt work. And I'm make another methods without i came back to main methods again, then I have a bugs with program.

starball
  • 20,030
  • 7
  • 43
  • 238
  • Hi. Besides `timer.cancel()` you should use `timer.purge()` as well. Check these answers: https://stackoverflow.com/a/16100989/20666497 and https://stackoverflow.com/a/1409132/20666497 – Albina Dec 19 '22 at 19:17
  • This not work , im try , i don't know where im must use this ? If im use timer cancel then my time schedule just stopped and I dont need this because my loop must have hp = 0 to cancel time, im try using , time.purge but I dont know how this is resolve my problem with public run void, ? Im try cancel public void and again load loop to get int hp = 0 – DraggyCords cords Dec 19 '22 at 19:50

0 Answers0