2

I have the following code, but I want it to run once every second, so if questNumber changes, then currentQuestStats will also change.

Editor's note: pastebin link with code that used to be here no longer works.

SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Betterjakers
  • 77
  • 2
  • 8

4 Answers4

3

use ScheduledExecutorService which added in JAVA 5, you must import following classes.

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

you can use it like below:

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // TODO add your code here:
    }
}, 0, 1, TimeUnit.SECONDS);

Answer

  • make a method called checkQuestNumber() in QuestsManagement class.
  • also create a constructor for QuestsManagement
  • initialize currentQuestStats with this value (§e§lCurrent quest: Kill 1 zombie).
  • make currentQuestStats and questNumber private and encapsulate them.

here is your QuestsManagement after those changes

public class QuestsManagement {

    private String currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
    private int questNumber = 1;

    public String getCurrentQuestStats() {
        return currentQuestStats;
    }

    public int getQuestNumber() {
        return questNumber;
    }

    QuestsManagement() {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
               checkQuestNumber();
            }
        }, 0, 1, TimeUnit.SECONDS);
    }

    void checkQuestNumber() {

        if (questNumber == 1) {
            currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
            // change manual!
            questNumber = 2;
        } else if (questNumber == 2) {
            currentQuestStats = "§e§lCurrent quest: Walk 100 blocks";
            // change manual!
            questNumber = 1;
        }
    }
}

To Test Code!

in your custom command file

create an instance of QuestsManagement and use getCurrentQuestStats() method

QuestsManagement m = new QuestsManagement();
player.addChatMessage("Test" + QuestsManagement.getCurrentQuestStats());
Rahmat Waisi
  • 1,293
  • 1
  • 15
  • 36
  • Later one (scheduledExecutorService)is a good approach!! – Praveen Kumar K S Jul 25 '16 at 04:47
  • Hello! Thanks for the reply. Where exactly do I put the last bit of code? (Where I create an instace of QuestsManagement and call checkQuestNumber())? – Betterjakers Jul 25 '16 at 05:08
  • hi, i edited the answer check it! – Rahmat Waisi Jul 25 '16 at 05:17
  • Thanks! Is there anyway to check if the code is working? I started up Minecraft, and went into a world. Sadly, I have not setup actually using the currentQuestStats, so I do not know if the code is working. – Betterjakers Jul 25 '16 at 05:22
  • @Betterjakers i added a `EDITS` part in answer, recheck it. – Rahmat Waisi Jul 25 '16 at 05:49
  • I joined the world, and nothing is happening in the console. Also, I am a bit confused on the "change manually" stuff. Anyway, thanks for the help you are giving me! – Betterjakers Jul 25 '16 at 05:59
  • I do not think the repeat every 1 second part of the code is working, as there is no console output, and the variable "currentQuestStats" does not change. – Betterjakers Jul 25 '16 at 06:03
  • @Betterjakers did you changed `checkQuestNumber` method as it is in `Edits` ? – Rahmat Waisi Jul 25 '16 at 06:10
  • What? I don't understand what you mean. I am sorry, but I am still learning Java. Your help is greatly appreciated! EDIT: Yes, I did change it as in Edits. – Betterjakers Jul 25 '16 at 06:11
  • @Betterjakers Good Luck man, i mean maybe your changes on code is wrong or is not as i answered, make sure your code is like [this](http://pastebin.com/s0bAq8gN), then run it and enjoy. – Rahmat Waisi Jul 25 '16 at 06:18
  • Hm.. alright. This is what I did: I made currentQuestStats a static, and in my custom command file, this is the code: player.addChatMessage("Test" + QuestsManagement.currentQuestStats); This should make it say this to me when I run the command: "TestCurrent quest: Kill 1 zombie". It does not, it only says "Test". That means currentQuestStats is not setting, and I don't know why. – Betterjakers Jul 25 '16 at 06:29
  • thats because `currentQuestStats` is empty string first(`""`) wait just a moment i fix them – Rahmat Waisi Jul 25 '16 at 06:39
  • @Betterjakers i changed some parts, [check this](http://pastebin.com/5xxYFmGr), im sure it's working now – Rahmat Waisi Jul 25 '16 at 06:45
  • It is not working, sadly. Here is my QuestsManagement: http://pastebin.com/16ddWPe2 and here is my command: http://pastebin.com/TLUV2ngb. I did everything you said, but it is not working. – Betterjakers Jul 25 '16 at 16:41
  • @Betterjakers make sure you initialize `currentQuestNumber` like ` String currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";` – Rahmat Waisi Jul 25 '16 at 16:46
  • Like this? http://pastebin.com/1Ge6yi0K This doesn't work, but I think it's what you mean. – Betterjakers Jul 25 '16 at 17:36
  • @RahmatWaisi Again, I don't know if it is doing that code every second, because nothing in there is working. It won't set currentQuestStats to "Curremt quest: Kill 1 zombie" when questNumber is 1. If I put "System.out.println("Test");" into the code, it does not say "Test" in console every second – Betterjakers Jul 25 '16 at 17:50
  • Read the answer again, it's clear now – Rahmat Waisi Jul 25 '16 at 17:51
1

Do it using multithreading. Here's the code:

public class QuestsManagement implements Runnable{
    public String currentQuestStats = "";
    public int questNumber = 1;
    Thread t;

    @Override
    public void run() {
        try {
            if(questNumber == 1) {
                currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
                if(questNumber == 2) {
                    currentQuestStats = "§e§lCurrent quest: Walk 100 blocks";
                }
            }
            Thread.sleep(1000);
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        Thread t = new Thread(new QuestsManagement());

        t.start();

        //do something else here... whatever you want to do
    }
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
1

First of all, you need to add all of the code you want to run to a method. I will assume you will call it update().

What you then want to do is add something like the following to your main program loop:

long nextTick = currentTimeMillis() + 1000 ;//Set time of first game tick

QuestsManagement quest = new QuestsManagement();

//Main Loop
while (true) {
    /*
    Do some other stuff
    */

    if (System. currentTimeMillis() >= nextTick) {//Check to see if it is time or past time to update
        nextTick += 1000//Set next tick to one second in the future
        quest.update();
    }
}

Please note that you are missing the update() method, the constructor, and any getters and setters. I would also refrain from making your variables public.

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33
theJack
  • 131
  • 1
  • 5
0

Well, there are multiple answers possible to this question. Java provides various ways to perform time operations. One approach is to use Timer class.

public class QuestsManagement {

public String currentQuestStats = "";
public int questNumber = 1;
static Timer t;
TimerTask task;
public static void main(String[] args) {
t = new Timer();
task = new TimerTask() {
        @Override
        public void run() {
            // TODO Auto-generated method stub

            if(questNumber == 1) {
                currentQuestStats = "§e§lCurrent quest: Kill 1 zombie";
            if(questNumber == 2) {
                 currentQuestStats = "§e§lCurrent quest: Walk 100 blocks";

         }
 } ;

t.scheduleAtFixedRate(task , 1000, 1000 );
}}

import following

import java.util.Timer;

import java.util.TimerTask;

Shaishav Jogani
  • 2,111
  • 3
  • 23
  • 33