Stuck inside an infinite While Loop :-/

Hi all,
When I write this program using the top-down structural method, it runs fine but when I use the call method inside the while loop, it doesn't test the "if" condition. It becomes a never-ending loop. :-/
import java.util.Random;
public class WhileLoop {
      public static void main(String[] args) {
        int random1;
        Random die1 = new Random();
        random1 = die1.nextInt(6) + 1;
        WhileLoop r = new WhileLoop();
        while (random1 != 5) {
          if (random1 != 5) {
           r.doRandom();
          if (random1 == 5) {
            System.out.println("you win! ");
         int random1;
      public void doRandom() {
         Random die1 = new Random();
         random1 = die1.nextInt(6) + 1;
         System.out.println("random1 = " + random1);
  }If I replace the line " r.doRandom(); " with " random1 = die1.nextInt(6) + 1; System.out.println("random1 = " + random1); " the program will check the "if" condition and stops when it finds the number 5. What's wrong with my code?
Thanks for your help.

DrLaszloJamf wrote:
{color:#3D2B1F }You have two, unrelated variables that happen to both be named random1.{color}Opps! Must have missed it. Using two unrelated variables with the same name was, unintentional ~ //yea, right (blush). Thanks for pointing it out. :-)
Encephalopathic wrote:
you never change random1 from within the while loop. You think you do, but it's a different random1 that you're changing, a non-static one that is an instance variable.okay~ but does it mean that 'random1' from the method within the while-loop cannot be used for comparison purpose? I tried using a 'return' value from the doRandom method and use that value inside the "if" condition, but it also does not terminate the loop. The only way it's going to work is by using the solution DrLaszlo gave? Is there any other way to do this by using a call method?
Thanks!

Similar Messages

  • How to out from infinite while loop in sub VI

    Dear Sir,
    how to out from infinite while loop in sub VI from main VI
    attached photo for solution but I can't understand it and i can't find the function in photo 
    please help
    Attachments:
    stop_subVI_frm_main.JPG ‏36 KB

    Asking how to get out of an infinite loop is like asking how to find the end of a circle. I'm not trying to be sarcastic but by definition, if there is a way out of the loop, then it is not infinite. I think what you are asking is how to avoid creating an infinite loop. Is there something about the suggestions you have been given that you do not like? My favorite suggestion is the notifier but maybe you just need an example. Turn on context help and read about the notifier functions in the code below.
    This is your top level VI
    And this is your subVI
    If this seems too complex then a global variable will work too. But what seems simpler can cause much more complex bugs. You can code fast and spend lots of time debugging or you can code slow and spend less time debugging. Personally I perfer writing productive code than looking for bugs any time.
    =====================
    LabVIEW 2012

  • UI flickrs continously jdk1.7.25 EventdispatchThread's pumpEventsForFilter goes to infinite while loop

    I am migrating a project from Java 1.3 to Java 1.7 update 25 and there is one search button functionality in which search is performed correctly but the UI flickers continuously because EventdispatchThread's pumpEventsForFilter goes to infinite while loop.
    This same code works correctly in java 1.3.
    Below is the part of the code related to searchbutton. Can you please suggest regarding this because the issue is within java api and not sure how to solve this.
    SearchButton.java:
    private JButton searchButton; 
    private String textsearchButton = 
          search.util.Language.getString("buttonStartSearch"); 
    searchButton = new JButton(textsearchButton); 
    buttonPanel.add(searchButton); 
    searchButton.addActionListener(this); 
    searchButton.addActionListener(actionListener); 
    actionListener.actionPerformed( 
                   new ActionEvent( 
                      searchButton, 
                      ActionEvent.ACTION_PERFORMED, 
                      "toFront")); 
                actionListener.actionPerformed( 
                   new ActionEvent( 
                      searchButton, 
                      ActionEvent.ACTION_PERFORMED, 
                      "searchComplete")); 
    setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 
        if (hasSearch) { 
                actionListener.actionPerformed( 
                   new ActionEvent( 
                      searchButton, 
                      ActionEvent.ACTION_PERFORMED, 
                      "searchComplete")); 
             else { 
                actionListener.actionPerformed( 
                   new ActionEvent( 
                      searchButton, 
                      ActionEvent.ACTION_PERFORMED, 
                      "search")); 
    searchButton.setEnabled(!hasSearch && hasCriterions()); 
    public void actionPerformed(ActionEvent ae) { 
          Object source = ae.getSource(); 
          else if (source == searchButton) 
             startSearch(); 
          else if (source == exportButton) 
             exportSearch(); 
          else { // ActionEvents from the panels occur 
             changesOccured(); 
    EventDispatchThread:
    void pumpEventsForFilter(int id, Conditional cond, EventFilter filter) { 
            addEventFilter(filter); 
            doDispatch = true; 
    //This while goes to infinite loop 
           [b] [color=red]while (doDispatch && !isInterrupted() && cond.evaluate()) { 
                pumpOneEventForFilters(id); 
            }[/color][/b] 
            removeEventFilter(filter); 

    Please provide your code example as SSCCE . I'm not going to spent time guessing what your application code (other than shown) meigt do or not do.
    bye
    TPD

  • Infinite While-loop!

    Hey there! I'm trying to do some data input validation but I haven't been able to figure it out. First I need to check if the user entered anything, that one works. Then I need to check if what the user entered was a number. But I'm getting an infinite while loop in when I try to validate if the first character entered is a letter. . . .
    Thanks for your help!
    public class methods
    public static void main(String args[]) throws IOException
      String input ="";
      int qoh=0;
      boolean error=true;
      Scanner keyboard = new Scanner (System.in);
      //while (error)
                    //   error=true;
                            while (error==true)
                                System.out.print("\nEnter Quantity on Hand: ");
                                input = keyboard.nextLine();
                                if (input.length() <1)
                                    System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                    error=true;
                                    System.out.println(qoh);
                                    System.out.println(input);
                                else
                                    error=false;
                            error = true;
                            while (error==true)
                                if (Character.isLetter(input.charAt(0)))
                                    System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                    error=true;
                                    System.out.println(qoh);
                                    System.out.println(input);
                                else
                                    qoh = Integer.parseInt(input);
                                    error=false;
            }

    1. add in breakpoints to your program.
    Eg. put print statements before and after loops to confirm which loop is producing the inf loop error.
    also add in print statements in your if and else blocks.
    2. You should consider using keyboard.next() instead of nextLine()
    Eg. how are you going to handle "500 orange crush"?
    3. I have a feeling that the real problem lies at the 2nd loop where you tried to do a parseInt
    What happens if you have "5lmao" charAt(0) check is passed, but it wont produce a int will it?
    You might want to loop through every char in the input string to confirm they are a number.
    4. I suggest
    If(input.length() > 0) error = false
    else print msg
    OR
    assume no errors before loop.
    if(length() <1) error=true
    else error = false
    5. use the keyword "break". By that i mean set up your loop to be infinite loops, use the break operator under specified condition (error=false)
    I didn't identify the error for you, but i'd say the above methods should help you with your problem

  • How do I break a for loop (inside) and a while loop (outside) at the same time by a control button

    I have a while loop (outside) and a for loop (inside) and a control button within the for loop.  I want to stop the program by click the botton without finishing the for loop.  How can I do that?
    Thank you in advance.

    HI Please find attached snapshot Regards, Santosh
    Message Edited by SanRac on 12-17-2009 05:12 AM
    Message Edited by SanRac on 12-17-2009 05:13 AM
    Attachments:
    Snap1.png ‏4 KB

  • How to avoid Build Array function inside a For (while) Loop?

    Hi there,
    I have a simple question about how to avoid using Build Array function inside the loop. Now I want to remove the Build Array funtion inside the loop to improve the performance (To get better memory management). Any idea how to do that?
    Thanks a lot!
    Warmest regards,
    Chong

    It's been my experience that using the auto-indexing to build an array
    on a For loop is just as good as initializing and replacing elements.
    The For loop knows before it runs how many iterations it has to run and
    can allocate the array ahead of time.
    You're better off initializing and replacing when using a While loop
    because it does not know how many iterations it will run and can't
    pre-allocate the array ahead of time.
    Ed
    Ed Dickens - Certified LabVIEW Architect - DISTek Integration, Inc. - NI Certified Alliance Partner
    Using the Abort button to stop your VI is like using a tree to stop your car. It works, but there may be consequences.

  • Infinite "while" loop subshell loses current date variable

    I have a simple script to log network connectivity to a set of systems.
    However, as expected the date appended to the log never changes because the new variable is lost when the loop starts again. Can someone clue me in on how to get around this issue?
    #!/bin/bash
    LOG=/tmp/netlog
    when=`/bin/date`
    while true;
    do
    for server in srv1 srv2 srv3 srv4 srv5;
    do
    ping -c 1 $server > /dev/null
    if [ $? -ne 0 ]; then
    echo "$server-DOWN!" $when >> $LOG.$server
    # mail
    else
    echo "$server-UP!" $when >> $LOG.$server
    fi
    done
    done

    esa wrote:Jason, from my experience, [] with quotes around variables is generaly more cross-over compatible (bsd'ish, deb'ish, rh'ish) than [[]] without quoting of variables.
    More than once i've had unexpected behaviour caused by using [[ condition ]].
    That's why you'd use /bin/bash instead of /bin/sh .. (or rather /usr/bin/env bash - OpenBSD has bash in /usr/local/bin) - [[ is bash specific.
    http://mywiki.wooledge.org/Bashism
    Last edited by Alad (2015-05-21 13:01:27)

  • Accidentally deleted /var/tmp directory and I'm now stuck in an infinite restart loop

    So guys, I was poking around and I accidentally deleted that file. I am now stuck in a restart loop that sometimes ends with a white kernel stop sign in front of  a black screen. When that happens, I am forced to restart my computer again.
    Every time I restart, the loading bar is about 1/5 of the way there when a series of messages show up on the top left of the screen. I took some pictures of the message, and I have inserted it below.
    Again, the directory is /var/tmp, and I am not sure if it was /private or not. I'm sorry.
    The kind person who fixes this issue will get my undying respect.
    Again, thank you guys very much.
    I own a 2012 15 inch MBP, if that helps.

    In addition to what greg sahli suggests, also issue the commands:
    chmod 1777 /var/tmp
    chown root:wheel /var/tmp
    My commands and greg sahli's suggestions ASSUME that you did not delete other things essential for the normal operation of Mac OS X.
    Otherwise you will have to follow mende1's advice and reinstall Mac OS X.

  • My new Iphone 6 is stuck in a infinite restart loop

    I just got my new Iphone yesterday and than I wake up the morning after and it's just flashing the apple logo for 20 seconds
    and then goes black for 2 seconds It is most disconcerting.

    Mine flashed a couple of times and went off and never came back on again, mine was 9 days old   take it to your nearest apple shop.

  • Can we place Analog in Read(AI-RE​AD) Vi inside the while loop for high sample rate like 22ks/s?

    I am using E-series Card for data acquisition.My requirement is to sample the channel, and check the 10 samples for certain condition.both at a time.What should be done can we place the AI-READ vi inside for or while loop for this purpose?

    Hello,
    Yes, you can include the AI Read.vi inside the while loop, you would just need to specify the number of scans to read for every iteration of the loop. Then, after AI Read.vi has read the data, you can do what ever kind of manipulation of the data you would like, before the next iteration of the loop. The one thing to watch out for is what ever manipulation of the data you do, be sure that it doesn't take to long whereas the buffer holding the data starts to back up. That can be checked by looking at the scan backlog output of the AI Read.vi, which will tell you how many scans have been acquired but haven't been read into your program.
    Hope this helps!
    Regards,
    Steven B.
    Applications Engineering, NI

  • I have a for loop inside of while loop.when i press stop for while loop, i also would like to stop for loop.how can i solve this problem?thanks

    i have a for loop inside of while loop.when i press stop for while loop, i also would like to stop for loop.how can i solve this problem?thanks

    Hi fais,
    Following through with what JB suggested. The steps involved in replacing the inner for loop with a while loop are outlined below.
    You can replace the inner for loop with a while by doing the following.
    1) Right-click of the for loop and select "Repalce" then navigate to the "while loop".
    2) Make sure the tunnels you where indexing on with the for loop are still indexing.
    3) Drop an "array size" node on your diagram. Wire the array that determines the number of iterations your for loop executes into this "array size".
    4) Wire the output of the array size into the new while loop.
    5) Set the condition terminal to "stop if true".
    6)Drop an "OR" gate inside the while loop and wire its output to the while loops condition terminal.
    7) C
    reate a local of the boolean "stop" button, and wire it into one of the inputs of your OR gate. This will allow you to stop the inner loop.
    8) Drop a "less than" node inside the inner while loop.
    9) Wire your iteration count into the bottom input of the "less than".
    10) Wire the count (see step 4 above) into the top input of the less than. This will stop the inner loop when ever the inner loop has processed the last element of your array.
    Provided I have not mixed up my tops and bottoms this should accomplish the replacement.
    I will let others explain how to takle this task using the "case solution".
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • PRS-T1 stuck in infinite reboot loop after failed firmware update

    Hi,
    I tried to update the firmware, but failed when updating to version 1.0.07.05070. Tried to 2 times. The first time it failed I simply tried again. The second time, it took a lot longer to reach the failed to update message, but it did cause the ereader to reboot.
    Now, it's stuck in an infinite reboot loop on the "Opening book" page. The progress bar on that page stays completely empty, lasts for about 30 seconds, and reboots again. This will go one until the battery is dead or indefinitely if plugged in. 
    I have tried pressing the Home + Menu buttons, but they seem to have no effect.
    Please advise if there is anything I can try to revive it?
    Thanks in advanced.
    David
    Solved!
    Go to Solution.

    Kiroken,
    Here is what I have observed:
    - After a hard boot (reset + power button during 3+ seconds), if I don't do anything, it will reboot every ~30seconds.
    - If I press and hold the Home and Menu buttons, no effect. The same as if I didn't press anything.
    - If I press the Forward + Back buttons (2 & 4), it does not reboot after 30 seconds. Instead, the orange light on the power button blink every ~2-3 seconds.
    - Any other key combinations that I have tried have no effect.
    I have tried with and without several rescue sdcard. No difference. No improvement. In every case, the computer never sees the reader. If plugged into the power outlet, it seems like the battery charges alright. It does not appear to charge if plugged into USB port.
    That's all I know. If I can't fix it, I might be forced to turn it into a coaster or maybe a cutting board for the kitchen.
    David

  • Error -50103 occured with timed loop inside a while loop

    Hello everyone,
    i wrote an application to sample analog voltage from  DAQ6024E card (see the attachments).
    I have a big while loop in the VI because a I want to add some other functions later.
    In the "WHILE_Cont Acq&Graph Voltage-Int Clk.vi" I use a while loop inside the big while loop to read the samples. It's working properly.
    but when I use a timed loop inside the big while loop (see "TIMED_LOOP_Cont Acq&Graph Voltage-Int Clk.vi"), I get an error -50103 from the timed loop.  It seems that the first cycle is ok, but after the first cycle the error occurs.
    I don't know what happens with the timed loop, anyone can help me? what does the error -50103 mean? thanks a lot!
    PS: I am using LabVIEW 8.0
    Message Edited by molo511 on 10-22-2006 05:21 AM
    Message Edited by molo511 on 10-22-2006 05:23 AM
    Attachments:
    TIMED_LOOP_Cont Acq&Graph Voltage-Int Clk.vi ‏143 KB
    WHILE_Cont Acq&Graph Voltage-Int Clk.vi ‏75 KB

    hi molo511,
    I tested your program but only with simulated devices. I had to delete the wire to the timing, so that the timed while loop runs with 1kHz. Did you already try this? Because this works on my PC.
    I also found a link in our database that might be interesting for you.
    http://digital.ni.com/public.nsf/websearch/04BEDD9E9E91ED3486256D180048116D?OpenDocument
    Greets
    Philipp N.
    NI Application Engineer

  • Exit a while loop inside an event case

    Hi All, I have a multi-page program. One of it is used to read some analog signal via a USB block continuously.
    What I want is when clicking this page, this while loop is activated. Then we can monitor the data. When we click other pages or "Stop" button, this while loop will be terminated. And we can use the other pages to do something else.
    Right now I got difficuties in stop the while loop. I do not want to stop the running of the whole program, just want to jump out of this while loop then do other operation.
    Could anyone give me some advise how to do it? Thank you very much! 

    Hi RavensFan, thank you for your reply.Actually this is not my real code  because the original one is very very compliacted.
    In real code, the tab control you see in inside the bigger while loop, that loop makes the whole program work.
    And as what I pointed, the purpose is when I click this tab (if we do not want it to trigger, we can place another "START" button to trigger), an internal while loop inside begins to run. This while loop keeps showing the real time analog signal.
    And if I do not want to use this "real time monitoring" function, I want to click somewhere (or doing anything else that can work) to jump out of this internal while loop and keep on using some other functions of the program.
    Could you advise about that? Thank you very much! 

  • Iphone stuck in infinite setup loop

    My iphone is stuck in an infinite setup loop. Have reset phone a lot of times and it lets me set up all info. I get home screen for less than 2 seconds and the set up screen pops back up. Randomly the voice over will come on and the tripple tap to enter from kep pad/board comes on or goes off. HELP!

    Hello DebiSuzi,
    Not being able to use your device can certainly be frustrating. From what I can gather, it sounds like you're having issues restarting your device. After reviewing your post, I have located an article that can help in this situation. You may want to consider restoring your device to factory settings. After this is complete, I would recommend restoring your data from any potential backups you may have:
    If you can't update or restore your iPhone, iPad, or iPod touch
    Use recovery mode
    You might need to use recovery mode to restore your device in these cases:
    iTunes doesn't recognize your device or says it's in recovery mode.
    You see the Apple logo onscreen for several minutes with no progress bar.
    You see the Connect to iTunes screen.
    Learn what to do if you see the progress bar onscreen for several minutes.
    To put your device into recovery mode, follow these steps:
    Turn off your device and leave it off.
    Plug in your device's USB cable to a computer with iTunes. 
    Hold down the Home button on your device as you connect the USB cable. Keep holding down the Home button until you see the Connect to iTunes screen.
    When you see this screen, release the Home button. If you don't see this screen, try steps 1 through 3 again. 
    When your device is connected, iTunes will open. You'll see a message saying that iTunes has detected an iPhone, iPad, or iPod touch in recovery mode.
    Use iTunes to restore your device. Restoring in recovery mode will erase your device. If you previously synced with iTunes or iCloud, you might be able to restore from your backup.
    Get more help
    Learn what to do if you don't see your device in iTunes for OS X, or in iTunes for Windows.
    If you put your device into recovery mode by mistake, restart it. Or you can wait 15 minutes and your device will exit recovery mode by itself.
    Thank you for contributing to Apple Support Communities.
    Cheers,
    BobbyD

Maybe you are looking for

  • Error trying to generate WSDL of webservice in JDeveloper 11.1.1.3

    Hey, Everytime I try to generate a WSDL of a webservice I get the following stack trace: java.lang.NullPointerException      at oracle.jdeveloper.webservices.model.java.JavaWebServiceValidator.getTypeReasons(JavaWebServiceValidator.java:882)      at

  • Missing Time Zone

    The 6120 Classic requires an additional time zone under the Australia setting as its missing. The Zone is +9.5hrs GMT and it is the Darwin (Northern Territory) zone.

  • Profile Management in XIr2

    Post Author: juanmontero CA Forum: Administration Hi all, I would like to ask you for some help about profile management. Actually i know the main process in order to setup profiles to filter information for each user, but here comes my problem, ther

  • Help me regarding iviews

    Hi SDN's, I m new to EP. My Question is smthing like wen i hav been created an iview and set on a page, i want to display dat iview in a full-page format. i mean wen i opend dat page, i dont want to click on iview to open on new page(open in new link

  • Red is not working in Ps

    I can not get the back to be red. It turns this color for the life of me. How do I fix that. Every other color by red works.