java timer on current instance

Posted by hspim on Stack Overflow See other posts from Stack Overflow or by hspim
Published on 2010-03-29T06:44:54Z Indexed on 2010/03/29 7:53 UTC
Read the original article Hit count: 304

Filed under:
|
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;


public class Boggle {
    Board board;
    Player player;
    Timer timer;
    boolean active;

    static Scanner in = new Scanner(System.in);

    public Boggle() {
        board = new Board(4);
        timer = new Timer();
    }

    public void newGame() {
        System.out.println("Please enter your name: ");
        String line = in.nextLine(); 
        player = new Player(line);
        active = true;

        board.shuffle();
        System.out.println(board);

        timer.schedule(new timesUP(), 20000);
        while(active) {
            String temp = in.nextLine();
            player.addGuess(temp);
        }
    }


    public void endGame() {
        active = false;
        int score = Scoring.calculate(player, board);
        System.out.println(score);
    }


    class timesUP extends TimerTask {
        public void run() {
            endGame();
        }
    }


    public static void main(String[] args) {
            Boggle boggle = new Boggle();
            boggle.newGame();

    }
}

I have the above class which should perform a loop for a given length of time and afterwards invoke an instance method. Essentially I need the loop in newGame() to run for a minute or so before endGame() is invoked on the current instance. However, using the Timer class I'm not sure how I would invoke the method I need on the current instance since I can't pass any parameters to the timertasks run method?

Is there an easy way to do this or am I going about this the wrong way? (note: this is a console project only, no GUI)

==========

code edited

I've changed the code to the above following the recommendations, and it works almost as I expect however the thread still doesnt seem to end properly. I was the while loop would die and control would eventually come back to the main method. Any ideas?

© Stack Overflow or respective owner

Related posts about java

Related posts about timer