#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    5
    Rep Power
    0

    Java seminary work - please help!


    I am writing a seminary work for my java programming lesson and its supposed to be a simple tank game. I have my Tank class with paint method:

    public void paint(Graphics g) {
    if (!isAlive) {
    return;
    }
    if (explode){
    g.drawImage(exp, x, y, null);
    explode = false;
    isAlive = false;
    return;
    }
    g.drawImage(tank, x, y, null);
    }

    class Game witch extends JPanel:

    public Level(int level) {
    this.setSize(500, 500);
    this.level = level;
    initTanks(); // Creates tank_list dependig on int level
    t = new Logics(tank_list); // Logics extends Thread and it is where all calculations are done
    }

    My first problem: When I create a new Level and and call t.run(), instead of repeating itself until terminating conditions are valid, the thread only does one iteration as if it was a simple method. Logics thread looks like this:

    public void run(){
    //here are terminating conditions, such as if player is dead, than return

    // and here follows the logics itself (for all tanks tank.move() etc.)
    }

    only when i surround it with do - while, it behaves like a thread (but i need it to work as a thread, do - while doesent help me)

    My second problem: Logics calculates everything correctly, but when I add (next to tank.move() ) tank.paint(g) so that tanks move and paint themselfs onto a new position as well, i get NullPointerException.

    Please, I realy need some advice here. Thanks!!
  2. #2
  3. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    only when i surround it with do - while, it behaves like a thread
    A thread will run through to completion. The logic within a run() method will not repeat unless given explicit instructions to do so. Control structures (such as do/while loops) and threads are orthogonal concepts.

    i get NullPointerException.
    In Java, the NullPointerException (NPE) is generally a simple exception to resolve. In very basic terms, it means that one is trying to access a property or call a method on an object that does not exist. Read the error message to find the line where the NPE occurred. Examine that line to determine which reference is a likely candidate to be null. Dig a little deeper to find out why that reference is null and fix the application to either ensure the reference is not null or to handle the reference gracefully if it is null.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    5
    Rep Power
    0
    Thanks. Well, i thought that when i call run() than it runs until i sleep it or stop it. So how do i explicitly tell run() method to keep running? And also when I call paint(g) it paints once correctly and when i call it again it throws NullPointerException. And nothing changed between the two calls.
  6. #4
  7. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    Well, i thought that when i call run() than it runs until i sleep it or stop it.
    That may be a common misunderstanding. As mentioned, a thread runs once, all the way through to completion. Also, you should start a new thread by calling the start() method, not run(). Something I neglected to mention earlier is that your "Logics" class should implement Runnable rather than extending Thread. Think of Thread as as the worker, and Runnable as the job. You should only extend Thread if you want to extend the functionality of the Thread class. This is rarely, if ever, needed.

    So how do i explicitly tell run() method to keep running?
    As you have described. Inside the run method, you tell your actions to repeat until some condition indicates it should stop.

    Example:
    Java Code:
    public void run() {
        while (running()) {
            doSomething();
        }
    }


    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    5
    Rep Power
    0
    Yes, well, I thought of calling start() instead of run() but for some reason, when i call start() it gives me an error message that it cant find symbol (symbol: method start() in class Logics) but Logics implements Runnable, so start() should be there automaticly, shouldnt it?
  10. #6
  11. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    Logics implements Runnable, so start() should be there automaticly, shouldnt it?
    No. Runnable (an interface) only declares one method: public void run(). I will repost the helpful link: http://java.sun.com/docs/books/tutor...runthread.html

    If you try to call a method on a type that does not have a visible method with a matching signature, you will get the infamous "cannot find" compiler error. And if you just call run() on a Runnable or a Thread, that execution will take place in the current thread, not a new one.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    5
    Rep Power
    0
    Yes, thanks for the link. Although i still cant see why the thread i created wouldnt work. I created it as an extends Thread class, overwritten its run() method so that it wouldnt stop until some condition wasnt completed and that way when i called it it only made a single iterration. However, when i put the run() method calling into the do while brackets, where in while there was exactly the same condition as in the run() method (condition that would stop it) than it repeat itself until the condition is completed.
  14. #8
  15. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    Although i still cant see why the thread i created wouldnt work.
    From here, it looks like your expectations and your instructions to the computer are not aligned well.

    However, when i put the run() method calling into the do while brackets, where in while there was exactly the same condition as in the run() method (condition that would stop it) than it repeat itself until the condition is completed.
    I am having trouble making sense of that sentence.

    The bottom line is that your program will do exactly what you tell it to. Perhaps the biggest challenge in early programming is with eliminating the difference between what you think you are telling the compiler and what you are actually telling the compiler.

    If you want your application to start a new thread, you will want to create a new Thread object and call its start() method. If you want the logic in the run() method to repeat, you will want to use a loop structure inside the run() method.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  16. #9
  17. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    Here is a trivial example:
    Java Code:
    import java.util.*;
     
    public class Foo {
        public static void main(String[] args) throws Exception {
            TypewriterJob tj = new TypewriterJob();
            new Thread(tj, "Jack Torrance").start();
     
            int aFewSeconds = 5000;
            Thread.sleep(aFewSeconds);
            tj.stopTyping();
            System.out.println("\n\nDone!");
        }
    }
     
    class TypewriterJob implements Runnable {
        private static final String MESSAGE = "All work and no play makes Jack a dull boy.\n";
        private boolean keepTyping = true;
     
        public void run() {
            Random rand = new Random();
            while (keepTyping) {
                for(char c : MESSAGE.toCharArray()) {
                    if (!keepTyping) break;
                    System.out.print(c);
                    pauseForAMoment(rand);
                }
            }
        }
     
        public void stopTyping() {
            keepTyping = false;
        }
     
        private void pauseForAMoment(Random rand) {
            int aFewMilliseconds= rand.nextInt(200);
            try {
                Thread.sleep(aFewMilliseconds);
            } catch (InterruptedException e) {
                // Don't worry about it
            }
        }
    }


    ~

    Comments on this post

    • mrider agrees : Although you might want to make that private [i]atomic[/i] boolean keepTyping = true;
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    5
    Rep Power
    0
    oh yeah, i get it now, at least i think i thought that thread would repeat itself until i call stop() method or somethink like it. But in order for the thread to repeat itself, i also need to create some loop with a terminating condition inside the run() method, right?
  20. #11
  21. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    i thought that thread would repeat itself until i call stop() method or somethink like it.
    No. Again, threads do not behave that way.

    But in order for the thread to repeat itself, i also need to create some loop with a terminating condition inside the run() method, right?
    Sort of. The thread is not repeating itself; the job is. The thread starts. The job runs (looping, if so instructed). The thread stops, never to be restarted again. That is what was described in replies #2, #4, and #8.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  22. #12
  23. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    mrider agrees: Although you might want to make that private atomic boolean keepTyping = true;
    I would, but then it wouldn't compile. There is no "atomic" keyword in Java.

    But you raise a very, very good point. It's just a trivial example focusing on the simple functionality of implementing a run() method that uses a loop, starting a thread, and stopping a job. But TypewriterJob is not a threadsafe class, so further work would be required for code that is intended for production use. It's always a good idea to consider thread safety and effective synchronization.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  24. #13
  25. <- My daily commute :^)
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2005
    Location
    Earth. Welcome.
    Posts
    1,500
    Rep Power
    1703
    Yikes! Got my programming languages mixed up C/C++! Oops. Funny, my spider sense was tingling the whole time I was typing that...

    Um, how about volatile?

    Anyway, that's the point was making - even if I wasn't doing it properly in Java
    A -> B: Ride.
  26. #14
  27. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Alpharetta, GA
    Posts
    1,809
    Rep Power
    1575
    Originally Posted by mrider
    Yikes! Got my programming languages mixed up C/C++! Oops. Funny, my spider sense was tingling the whole time I was typing that...
    If you read that link, you'll see that atomic is something which the TARIFA tool is adding to the language (in the form of a macro and some rather hinky assembly language post-processing); C and C++ have no language-native threading at all, but rely on thread libraries such as pthreads.

    Originally Posted by mrider
    Um, how about volatile?
    In C/C++, that is a keyword, but it means just the opposite of what you had in mind - a volatile variable is one which may be altered by some other program without warning. The keyword is used to indicate to the compiler not to perform certain types of optimizations, because the value can change even if the local code does nothing to it.
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov

IMN logo majestic logo threadwatch logo seochat tools logo