Results 1 to 5 of 5
  1. #1
    voider is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default Modify variable while loop from "outside"

    Hi

    What I'm trying to do is modify a global variable from outside while my programm is in a loop. The point of this is to be able to stop the loop at all times just by clicking a button.

    boolean startState;

    ...

    while(startState!=false)
    doSomething();

    ....

    if button pressed -> startState = false;


    I noticed that the variable is changed only after the loop finishes by itself ...
    Is there a way to do this ? Heard something about multithreading, but im not sure how to implement that one.

    Tks in advance

  2. #2
    Addez is offline Senior Member
    Join Date
    Aug 2009
    Posts
    294
    Rep Power
    0

    Default

    boolean startState = true;

    ...

    while(startState){

    doSomething();
    if button pressed -> startState = false;

    }

    Gota include the check if button pressed inside the startState loop.

  3. #3
    imorio is offline Senior Member
    Join Date
    Aug 2010
    Posts
    127
    Rep Power
    0

    Default

    Yes, multi-threading is the way to go:

    1. put the while loop in a methode called "public void run()" in a seperate class (if you need to have some variabele availebel for the while-loop, add them as class variabeles via the constructor).

    2. make that class extend the Thread class.

    3. make a new instance of that class

    4. call a methode called "start()" on that instance. Voilá, your while-loop starts running, but your program also goes to the next line after the "start()" line, leaving you with the posibility to change variabeles in that instance by calling methodes on it. Meanwhile, the while-loop keeps running.

  4. #4
    voider is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    tks imorio. that really sounds like a solid idea. I'll try to implement it in a moment

  5. #5
    voider is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    Ok managed to implement it via multi threading. thanks a lot for the tip

Similar Threads

  1. Error "variable is never read"
    By Phitur in forum New To Java
    Replies: 6
    Last Post: 09-07-2010, 05:30 AM
  2. An "if" statement inside a "for" loop?
    By soccermiles in forum New To Java
    Replies: 18
    Last Post: 04-20-2010, 03:44 AM
  3. Error "can not find symbol variable"
    By FullMetalHollow in forum New To Java
    Replies: 5
    Last Post: 10-04-2009, 09:51 PM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •