简体   繁体   中英

How can I reuse a procedure that throws an exception?

The aim of this code is for a timer of 5 seconds to start after each tick, allowing the user 5 seconds to enter an input after each tick. Now I have seen other methods of doing this such as System.currentTimeMillis(); , but I don't think that this will work for this instance.

  import java.util.Scanner; // Imports scanner utility
  import java.util.Random; // Imports the random utility to generate a random number.
  import java.lang.Math; // Imports the math utility used for mathematical functions.
  import java.util.concurrent.TimeUnit; // Time utility used for time related functions.
  import java.util.Timer;
  import java.util.TimerTask;
  import java.io.*;

  class alienPet
  {
    alien ufo = new alien(); // The alien is created outside of a class so that it can be altered in different methods.
      public static void main (String[] param)
      {
          // We want to call all of the functions
          // and procedures to make an interactive
          // alien program for the user.
          alienPet a = new alienPet();
          a.welcomeMessage(); // The class a is created in order to call non-static methods from a static method.
          a.alienCreation();
          a.tick();

          // System.exit(0);

      } // END main

        /* ***************************************
        *   Define a method to obtain the users input
        * and start the correct method.
        */

        public String userInput (String message)
        {
          Scanner scan = new Scanner(System.in);
          String inp;
          if (message.equals("")){

          }else{
            print(message);
          }
          inp = scan.nextLine();
              return inp;
        } // END userInput

        /* ***************************************
      * Define a method to print messages.
      */

      public void print (String message)
      {
          System.out.println(message);
          return;
      } // END print

      /* ***************************************
      * Define a method to welcome the user to the game
      * and enlighten them on how to play.
      */

      public void welcomeMessage ()
      {
        print("Thank you for playing the pet alien game");
        print("In this game, you will have to look after your own alien.");
        print("There is multiple aspects to looking after your alien, such as:");
        print("Hunger, Behaviour and Thirst.");
        print("The game ticks every five seconds, with the hunger and thirst levels dropping with each tick.");
        print("");
        print("When prompted, you can use the following commands:");
        print("feed -> Replenishes alien to max hunger level");
        print("drink -> Replenished thirst level to max");
        print("exit -> Will end the game immediately.");
        print("");
          return;
      } // END welcomeMessage


      /* ***************************************
      * Define a method to create alien
      */

      public void alienCreation ()
      {
        ufo.name = userInput("What would you like to name your new alien?");
        ufo.hungerRate = ranNum(1, 6);
        print("Congratulations on your new alien, " + ufo.name);
        print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
        alienBehaviour(ufo.hungerRate);
          return;
      } // END alienCreation

      /* ***************************************
      * Define a method to display the current
      * behaviour of the alien
      */

      public void alienBehaviour (int hunger) {
          if (hunger <= 2){
              print(ufo.name + " is very hungry, and is dangerously angry!!");
              String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("That is a dangerous decision.");
              }
          }else if (hunger <= 4) {
            print(ufo.name + " is mildly hungry, but is in a calm state.");
              String action = userInput("Would you like to take any actions?");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("Okay.");
              }
          }else if (hunger <= 6) {
            print(ufo.name + " is not hungry and is in a happy state.");
              String action = userInput("Would you like to take any actions?");
              if (action.equals("feed")){
                  feedAlien();
              }else if (action.equals("drink")) {
                  alienDrink();
              }else{
                  print("Okay.");
              }
          }
      } // END alienBehaviour

      /* ***************************************
      * Define a method to feed the alien
      */

      public void feedAlien() {
          ufo.hungerRate = 6;
          print(ufo.name + "'s hunger level replenished to max level 6.");
          print(ufo.name + " is now at a happy level.");
      } // END feedAlien

      /* ***************************************
      * Define a method to hydrate the alien
      */

      public void alienDrink() {
        ufo.thirst = 6;
        print(ufo.name + "'s thirst level replenished to max level 6.");
      } // END alienDrink

    /* ***************************************
      * Define a method to do an in-game tick
      */

    public void tick() {
        print("");
        ufo.age++;
        if (ufo.age == 100) {
            print("It is a sad day.");
            print(ufo.name + " has finally reached the age of 100 after a good life and has gone to the after life.");
            print("Well done!");
            System.exit(0);
        }
        if (ufo.hungerRate < 0){
            print("Oh no! " + ufo.name + " has died of hunger!");
            print("GAME OVER!");
            ufo.alive = false;
            gameEnd();
        } else if (ufo.thirst < 0){
            print("Oh no! " + ufo.name + " has died of dehydration!");
            print("GAME OVER!");
            ufo.alive = false;
            gameEnd();
        }else {
            print(ufo.name + "'s current stats:");
            print("-Hunger level = " + ufo.hungerRate);
            print("-Hydration level = " + ufo.thirst);
            print("-Age = " + ufo.age + " days old");
            print("");
        }
        if (ufo.hungerRate > 0){
            if (ufo.age % 2 == 0) {
                if (ufo.hungerRate <= 2){
                print(ufo.name + " is very hungry, and is dangerously angry!!");
                }else if (ufo.hungerRate <= 4) {
                print(ufo.name + " is mildly hungry, but is in a calm state.");
                }else if (ufo.hungerRate <= 6) {
                print(ufo.name + " is not hungry and is in a happy state.");
                }
            }
        }
        ufo.hungerRate--;
        ufo.thirst--;
        try{
            getInput();
        }
        catch (Exception e) {

        }
        finally{
            tick();
        }
    } // END tick

    private String act = "";

    TimerTask task = new TimerTask()
    {
        public void run()
        {
            if( act.equals("") )
            {
                tick();
            }
        }    
    };

    /* ***************************************
      * Define a method to get a user input
      * with a time limit of 5 seconds.
      */

    public void getInput() throws Exception
    {
        Timer timer = new Timer();
        timer.schedule( task, 5*1000 );

        BufferedReader in = new BufferedReader(
        new InputStreamReader( System.in ) );
        act = in.readLine();

        timer.cancel();
        if (act.equals("feed")){
            feedAlien();
        }else if (act.equals("drink")) {
            alienDrink();
        }else if (act.equals("exit")) {
            gameEnd();
        }
        tick();

    } // END getInput

    /* ***************************************
      * Define a method to end the game and
      * display the results
      */

    public void gameEnd() {
        if (ufo.alive == false) {
            print("Your alien, " + ufo.name + ", lasted " + ufo.age + " days.");
        }else {
            print("Well done you kept your alien, " + ufo.name + ", alive for " + ufo.age + " days.");
        }
        System.exit(0);
    }

      public int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
        Random random = new Random();
        return random.ints(min,(max+1)).findFirst().getAsInt();
    } // END ranNum

  } // END class alienPet

  class alien {
      String name;
      int age = 0;
      int hungerRate;
      int thirst = 6;
      Boolean alive = true;
  }

The procedure that is throwing the exception is getInput() , I want to reuse this but it seems as if the timer will only start once and will not start again, so tick() is just cycled over and over immediately. As I am a java amateur, any help would be greatly appreciated.

A TimerTask cannot be reused across Timers. To solve this particular problem create a new TimerTask each time you need to schedule for tick to run.

private getTimerTask(){
    return new TimerTask()
    {
        public void run()
        {
            if( act.equals("") )
            {
                tick();
            }
        }    
    };
}

And in getInput()

timer.schedule( getTimerTask(), 5*1000 );

Though this might work, would suggest to instead try use a single timer that runs every 5 seconds instead of creating one for each input call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM