While loop problems

hey guys,
i made a program that counts any system with single character values (binary, ternary, octal, decimal,...etc) I am asking the user to input a starting point to count from and a stoping point to stop at. It starts from the correct place but does not stop.
For some reason it is ignoring my while loop condition. anyone got any idea why this would happen?
import javax.swing.*;
import java.util.*;
class Counting
     public static void main(String[] args)
          String input,start,stop,s;     
          int spaces;
          input = JOptionPane.showInputDialog("Enter number of spaces.");
          spaces = Integer.parseInt(input);
          s = JOptionPane.showInputDialog("Enter counting symbols in sorted order.");
          start = JOptionPane.showInputDialog("Enter the stating number. (" + spaces + " characters).");
          stop = JOptionPane.showInputDialog("Enter the number to stop at. (" + spaces + " characters).");
          StringBuffer num = new StringBuffer(start);
          int lspace = spaces - 1;
          int i,j;
          String k,z;
          System.out.println(num);
          while(num.equals(stop)!=true)
               k = Character.toString((num.charAt(lspace)));
               z = Character.toString((s.charAt(s.length()-1)));
               if(k.equals(z)==false)
                    i = s.indexOf(num.charAt(lspace));
                    num.setCharAt(lspace, s.charAt(i+1));
               else
                    num.setCharAt(lspace, s.charAt(0));
                    lspace--;
                    i = s.indexOf(num.charAt(lspace));
                    num.setCharAt(lspace, s.charAt(i+1));
                    lspace = spaces - 1;
               System.out.println(num);
          System.exit(0);
}

i got it to work.
here is the if anyone is interested. Thank for the help!
import javax.swing.*;
import java.util.*;
class Counting
     public static void main(String[] args)
          String input,start,stop,s;     
          int spaces;
          input = JOptionPane.showInputDialog("Enter number of spaces.");
          spaces = Integer.parseInt(input);
          s = JOptionPane.showInputDialog("Enter counting symbols in sorted order.");
          start = JOptionPane.showInputDialog("Enter the stating number. (" + spaces + " characters).");
          stop = JOptionPane.showInputDialog("Enter the number to stop at. (" + spaces + " characters).");
          StringBuffer num = new StringBuffer(start);
          int lspace = spaces - 1;
          int i,j;
          String k,z;
          System.out.println(num);
          while(!num.toString().equals(stop))
               k = Character.toString((num.charAt(lspace)));
               z = Character.toString((s.charAt(s.length()-1)));
               if(k.equals(z)==false)
                    i = s.indexOf(num.charAt(lspace));
                    num.setCharAt(lspace, s.charAt(i+1));
               else
                    while((Character.toString((num.charAt(lspace)))).equals(z)==true)
                         num.setCharAt(lspace, s.charAt(0));
                         lspace--;
                    i = s.indexOf(num.charAt(lspace));
                    num.setCharAt(lspace, s.charAt(i+1));
                    lspace = spaces - 1;
               System.out.println(num);
          System.exit(0);
}

Similar Messages

  • Do while loop problem

    I have a problem with do while loop. I am displaying a dialogue box where a person should enter the type of quiz he had performed. The problem is that the user should enter only the following 3 words, either "Earthquakes" or "Place" or "Animals". If the user enters any other word, he/she should be displayed wwith another message saying "Invalid". This should keep repeatinf (i.e. displaying invalid) until the user enters either of those 3 words. When a user enters one of those words it will stop diplaying "Invalid". I tried doing this, but altough it displays "Invalid" when a user enters an invalid word, it will display invalid also when a user neters the correct word. I think i have something wrong with the loop.
    This is the code:
         String player = JOptionPane.showInputDialog(null, "Enter name");
                 String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
                do
                    type = JOptionPane.showInputDialog(null, "Invalid entry. Try again." );
                 while (type != "Earthquakes"  || type != "Place" || type != "Animals" );

    Yeah thats a good idea, but i'm still a beginner and i'm still new to some things. I got a problem, because altough the while loop is working correctly, however the first time i enter a word even if its correct its still displays invalid. I think that thats a property of the while loop. So can someone pls tell me how can i change this loop and use another loop that wouldn't do this. Can i use perhaps a for loop instead here? Thanks a lot.
    String player = JOptionPane.showInputDialog(null, "Enter name");
              String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
                  do {
                      type = JOptionPane.showInputDialog(null, "Invalid entry. Try again." );
                   } while(!type.equals("Earthquakes") && !type.equals("Places") && !type.equals("Animals"));
                Edited by: datax on Feb 21, 2008 10:46 AM

  • While loop problem

    I have a problem with a while loop in this code and it is really holding me up doing my degree. I can see nothing wrong with it but perhaps someone here can help. I would be really greatful if someone could. I have commented the line where the while loop starts about a third of the way down the code.
    Thanks
    Michael
    if (ae.getSource()==client_open)
    int row=0;
    check=true;
    row=client_listing.getSelectedRow();
    try
    System.out.println("information[row][1] is "+information[row][1]);
    if(information[row][1]!=null) //if the index is not null. Comment out this if statement to troubleshoot
    try
    InetAddress inet=InetAddress.getByName(information[row][1]);
    //Create a client socket on the listeners machone on port 7070
    client_socket=new Socket(inet,7070);
    System.out.println("Client port open on 7070 ");
    //Get the output as well as the input streams on that socket
    BufferedOutputStream out=new BufferedOutputStream(client_socket.getOutputStream());
    BufferedInputStream br_socket=new BufferedInputStream(client_socket.getInputStream());
    XMLWriter writer=new XMLWriter();
    writer.requestFString("SHOWFILES"," ");
    String file_data=writer.returnRequest();
    byte file_bytes[]=file_data.getBytes();
    int file_size=file_bytes.length;
    byte b[]=new byte[1024];
    // The methos takes a byte array and it's length as parameters and return
    // a byte array of length 1024 bytes....
    add_on upload=new add_on();
    System.out.println("Class of add_on created sucessfully");
    b=upload.appropriatelength(file_bytes,file_size);
    out.write(b,0,1024);
    /*An output stream is also initialised. This is used to store all the response
    from the listener */
    BufferedOutputStream out_file=new BufferedOutputStream(new FileOutputStream("response.xml"));
    int y=0;
    byte f[]=new byte[32];
    System.out.println("Entering while loop");
    //This while loop is not working. Any ideas. It just hangs here
    while((y=br_socket.read(f,0,32))>0) //the socket input stream is read
    out_file.write(f,0,y); //written on to the file output stream, y bytes from f start @ ofset 0
    out.close();
    br_socket.close();
    out_file.close();
    System.out.println("Exited while loop and closed streams");
    catch(Exception e)
    client_socket=null;
    check=false;
    System.out.println("Didnt enter try");
    try
    client_socket.close();
    catch(Exception e)
    System.out.println("Error occuered "+e.getMessage());
    row=0;
    if(check) //If the exception occurs then do not come here
    Vector parameters=new Vector();
    // A class SParser is also used here this class has a function/method of
    // the name perform which calls the xml parser to parse the xml file
    // generated by the response from the client soket...
    // the function perform returns a Vector which has the files/directories,
    // along with their flag information and size in case of files....
    SParser sp=new SParser();
    System.out.println("SParser object created sucessfully");
    parameters=sp.perform("response.xml");
    System.out.println("Parsing finished ");
    // The vector value returned by the xml parseris then passed as one of
    // the parameters to a class named file_gui this class is responsible for
    // displaying GUI consisting of a table and some buttons along with the
    // root information and flag..
    // Initially since the class is called for the first time the parameter
    // for the root is given the name "ROOT" and the Flag is set to "0"..
    file_gui showfiles=new file_gui(parameters,information[row][1],"Root","0");
    showfiles.show();
    check=false;
    } //end if
    } // end if
    } //end try
    catch(Exception e)
    row=0;
    } //end of ae.getSource()

    Why do you think it hangs at the while loop, eh? You need to put in additional printlns to justify your assertion. It takes alot less time to diagnose if you put in specific try/catch blocks with their own printlns - even if it is not as much fun. When you get into these kinds of troubles, there is no shame in putting in prints at each statement or logical point to track down the actual fault.
    ~Bill

  • Sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loop

    sir i have given lot of effort but i am not able to solve my problem either with notifiers or with occurence fn,probably i do not know how to use these synchronisation tools.

    sir i am using datasocket read ,i am communicating with java but my problem is that bcz im using while loop to see if value has changed my labview consumes all the processors time ,sir i want a event like thing so that while loop is not in continuous loopHi Sam,
    I want to pass along a couple of tips that will get you more and better response on this list.
    1) There is an un-written rule that says more "stars" is better than just one star. Giving a one star rating will probably eliminate that responder from individuals that are willing to anser your question.
    2) If someone gives you an answer that meets your needs, reply to that answer and say that it worked.
    3) If someone suggests that you look at an example, DO IT! LV comes with a wonderful set of examples that demonstate almost all of the core functionality of LV. Familiarity with all of the LV examples will get you through about 80% of the Certified LabVIEW Developer exam.
    4) If you have a question first search the examples for something tha
    t may help you. If you can not find an example that is exactly what you want, find one that is close and post a question along the lines of "I want to do something similar to example X, how can I modify it to do Y".
    5) Some of the greatest LabVIEW minds offer there services and advice for free on this exchange. If you treat them good, they can get you through almost every challenge that can be encountered in LV.
    6) If English is not your native language, post your question in the language you favor. There is probably someone around that can help. "We're big, we're bad, we're international!"
    Trying to help,
    Welcome to the forum!
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Problem with DAQ in while loop and Graphs

    Hello,
    I'm new here so I apologize if I posted this on the wrong board  
    This is my "situation":
    I need to make a simple PID controller which takes information (process variable) from an outside source (a NI's DAC connected through the USB port ) which is accomplished using NI-DAQ as an input, and the PID's output goes to the second NI-DAQ which is also connected using DAC to an actuator which in my case regulates the air pressure. (VI attached)
    My problem is the following.
    Both of the NI-DAQ I placed using DAQ Assist, require to be in a while loop.
    -If I place them in separate loops, I have the problem of passing information between the Input NI-DAQ and the PID, and also between the PID and the Output NI-DAQ.
    -If I place them both in one big loop, an error occurs saying that the selected buffer size is too small (Error -200609).
    The timing settings for the DAQ's N samples, 100 samples to read at the rate of 1k (I also tried with Continuous samples and many different combinations of Samples to Read an Rate but without success).
    Should I wire them with the same dt(s)?
    The other thing I need to do (I'm also writing it here in order not to open new topics) is show the following 3 signals on a Graph (process variable (dynamic data type)(range 4mA - 20mA), PID output (double)(range 4mA - 20mA), and the Set Point (double)(range 0 to inf))
    Firstly, is it possible to show the first two on a scale from 0 to 100 without changing the PID's output which needs to be 4-20?
    Secondly, which graph should I use if I have different data types? (I tried the Waveform Chart, and succeeded in showing the first two; the third just messes everything up)
    I would also have to make a legend explaining which signal is which (I see that this is possible with the Mixed Signal Graph).
    I know this is probably too much to ask, but I'd be grateful for any help
    Thank you in advance
    Attachments:
    PID while.vi ‏100 KB

    My problem is the following. Both of the NI-DAQ I placed using DAQ Assist, require to be in a while loop.
    -If
    I place them in separate loops, I have the problem of passing
    information between the Input NI-DAQ and the PID, and also between the
    PID and the Output NI-DAQ.
    This is the best option---Use QUEUE or Functional global or something else to tranfer the data to and fro
    How  do I make that QUEUE or Functional global?
    -If I place them both in one big loop, an error occurs saying that the selected buffer size is too small (Error -200609).
    Have
    you tried increasing the buffer? Is the acquisition happening
    parallelly (means to say the first DAQ not wired (error terminal) to
    second DAQ)
    Well the buffer is, at least how I understood it, the option Number of Samples when in Continuous Samples mode. Concerning the parallel acquisition, do you mean I should wire the error ports of both of the DAQs?

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • 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

  • Problem using while loop with !=

    Hi, I'm a beginner and still learning the basics of Java!
    Right now, I have a problem creating a while loop to read in two values.
    This is what I have entered:
    while((input != 'a') || (input != 'b'))
           Screen.out.println("Invalid Input");
           Screen.out.println("Enter 'a' or 'b' to continue");
           input = Keybd.in.readChar();
    }    I'm trying to get a input from the user, either the character 'a' or 'b' to continue, where my next set of code would come in and if they did not enter the character 'a' or 'b', it would display the "Invalid Input" message.
    What I can't get to happen in my while loop is that when I enter 'a' or 'b' , I still get the "Invalid Input" message etc. Even when I enter any other character in, I still get the same "Invalid Input" message. I thought the " != " mean "not equal to" and the " || " means OR. What am I doing wrong??

    while((input != 'a') && (input != 'b'))The || operator evaluates to true if either operand is true. If you enter an 'a', (input != 'b') is true, so the code gets executed. Similarly, if you enter 'b', you obviously didn't enter an 'a', so your code gets executed.
    You want to execute the code only if (input != 'a') AND (input != 'b').
    ~

  • Problem with avi recording and parallel while loops

    Hi,
    I made a test-VI which captures my webcam and save it to an AVI. (based on a sample I found somewhere)
    This works pretty fine so far (except the fact that the "frames per second"-constant has no effect and I am not able to change the resolution, but that's not the problem).
    I have a VI which controls some hardware and I want to record this with the webcam. For testing I made a dummy-VI which should run in parallel with the VI above:
    The 1st while loop should capture the webcam.
    In the 2nd while loop is a dummy-VI which generates some random values and waits 5000ms (to simulate the hardware).
    The problem is that those while loops do not work in parallel. When the execution is finished I get an AVI-file which is about 100ms long (so I guess it captures just 1 frame).
    If I replace that whole dummy-VI thing with a stop button it works nicely, but if I try to use a "Wait (ms) Function" or a "Wait Until Next ms Multiple Function" the video is always just about 100ms.
    Any idea how to implement multitasking or maybe even multithreading ?
    Attachments:
    lv_avi-recording.png ‏23 KB

    Hi Chris3,
    Just a random suggestion but have you tried removing the sequence structure? You can wire the error cluster from the IMAQdx Configure Grab.vi to both of the VIs for it to start parallely. 
    If you put it in a sequence like that, it is most likely that the middle sequence has to complete execution before it can go to the next sequence but it couldn't because of the wait.
    Let me know how it goes.
    Warmest regards,
    Lennard.C
    Learning new things everyday...

  • Problem with Do-While Loop in a Binary Search

    The idea of the program is to randomly generate 10 integers, store them in an array then use a binary search to find the values at each position of the array in 10 or less steps.
    My problem is that the do-while loopisn't doing what it should be and I can't see the problem :S
    Thanks in advance.
    Se�n.
    int counter=0, guess=500, MIN=0, MAX=0;
    int arr[] = new int[10];
              for(int i=0; i<10; i++) {
          int ranNum= ( (int)(Math.random()*1000)+1 );
          arr=ranNum;
         System.out.println(ranNum);
         for(int j=0; j<10; j++) {
              do{
                   if(guess>arr[j]){
                        guess=MAX;
                        guess=guess/2;
                   else if(guess<arr[j]){
                        guess=MIN;
                        MAX=MIN*2;
    guess=((MAX-MIN)/2)+MIN;
                   else
                        guess=arr[j];
    }while(guess!=arr[j]);
              System.out.println("The number at position "+j+" in the array is :"+arr[j]);
    //resets the values each time the do-while loops breaks
              MIN=0;
              MAX=0;
              guess=500;

    Looks toe like MAX and MIN are always going to be zero.

  • Problems with a while loop within a method... (please help so I can sleep)

    Crud, I keep getting the wrong outputs for the reverseArray. I keep getting "9 7 5 7 9" instead of "9 7 5 3 1". Can you guys figure it out? T.I.A (been trying to figure this prog out for quite some time now)
    * AWT Sample application
    * @author Weili Guan
    * @version 1999999999.2541a 04/02/26
    public class ArrayMethods{
       private static int counter, counter2, ndx, checker, sum, a, size, zero;
       private static int length;
       private static int [] output2, output3, reverse, array;
       private static double output;
       private static double dblsum, dblchecker, average;
       public static void main(String[] args) {
          //int
          //int [] reverse;
          System.out.println("Testing with array with the values [1,3,5,7,9]");
          size = 5;
          array = new int [size];
          reverse = new int [size];
          array[0] = 1;
          array[1] = 3;
          array[2] = 5;
          array[3] = 7;
          array[4] = 9;
          System.out.println("Testing with sumArray...");
          output = sumArray(array);
          System.out.println("Sum of the array: " + sum);
          System.out.println();
          System.out.println("Testing with countArray...");
          output = countArray(array);
          System.out.println("Sum of the elements : " + checker);
          System.out.println();
          System.out.println("Testing with averageArray...");
          output = averageArray(array);
          System.out.println("The average of the array : " + average);
          System.out.println();
          System.out.println("Testing with reverseArray...");
          output2 = reverseArray(array);
          output3 = reverseArray(reverse);
          //System.out.print(reverse[4]);
          System.out.print("The reverse of the array : ");
          for(ndx = 0; ndx < array.length; ndx++){
             System.out.print(reverse[ndx] + " ");
       private ArrayMethods(){
       public static int sumArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if (array[ndx] > 0){
                checker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                sum += array[ndx];
                ndx++;
             return sum;
          else{
             sum = 0;
             return sum;
        /*Computes the sum of the elements of an int array. A null input, or a
        zero-length array are summed to zero.
        Parameters:
            array - an array of ints to be summed.
        Returns:
            The sum of the elements.*/
       public static int countArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if(array[ndx] > 0 && array[ndx] != 0){
                checker++;
             counter++;
          return checker;
        /*Computes the count of elements in an int array. The count of a
        null reference is taken to be zero.
        Parameters:
            array - an array of ints to be counted.
        Returns:
            The count of the elements.*/
       public static double averageArray(int[] array){
          dblchecker = 0;
          ndx = 0;
          counter = 0;
          dblsum = 0;
          while(counter < array.length){
             if(array[ndx] > 0){
                dblchecker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                dblsum += array[ndx];
                ndx++;
             average = dblsum / dblchecker;
             return (int) average;
          else{
             average = 0;
             return average;
        /*Computes the average of the elements of an int array. A null input,
        or a zero-length array are averaged to zero.
        Parameters:
            array - an array of ints to be averaged.
        Returns:
            The average of the elements.*/
       public static int[] reverseArray(int[] array){
          ndx = 0;
          counter = 0;
          counter2 = 0;
          if(array.length == 0){
             array[0] = 0;
             return array;
          else{
                //reverse = array;
             while(ndx <= size - 1){
                   reverse[ndx] = array[4 - counter];
                   counter++;
                   ndx++;
                   System.out.print("H ");
          return reverse;
        /*Returns a new array with the same elements as the input array, but
        in reversed order. In the event the input is a null reference, a
        null reference is returned. In the event the input is a zero-length array,
        the same reference is returned, rather than a new one.
        Parameters:
            array - an array of ints to be reversed.
        Returns:
            A reference to the new array.*/
    }

    What was the original question? I thought it was
    getting the desired output, " 9 7 5 3 1."
    He didn't ask for improving the while loop or the
    reverseArray method, did he?
    By removing "output3 = reverseArray(reverse):," you
    get the desired output.Okay, cranky-pants. Your solution provides the OP with the desired output. However, it only addresses the symptom rather than the underlying problem. If you'd bother yourself to look at the overall design, you might see that hard-coding magic numbers and returning static arrays as the result of reversing an array passed as an argument probably isn't such a great idea. That's why I attempted to help by providing a complete, working example of a method that "reverses" an int[].
    Removing everything and providing "System.out.println("9 7 5 3 1");" gets him the desired output as well, but (like your solution) does nothing to address the logic problems inherent in the method itself and the class as a whole.

  • Problem with two parallel While loops

    I have a serious problem with controlling two parallel While Loop. Here is the deal:
    I have written a VI to send a series of commands called Cycle through Serial Port to a custom hardware. One of these commands is setting motor pressure by sending it's command and changing it's voltage. After setting desired pressure I have to read and control motor pressure, again through serial port in a parallel loop. There is a Pressure Sensor in system and I can obtain current's motor pressure by sending a command and receiving pressure value. In the first While loop I send some commands to hardware including Pressure Setting Command trough a state machine. In the second While Loop I read pressure value and then decide to increase motor voltage or decrease  it. Now the problem is in communicating these two loops. In cycle after "Init" state when state reaches "Pressure 2 Bar" motor voltage will increase. Meanwhile I have to control this voltage in parallel While Loop. As you can see I used Local Variable to communicate between these two loops. The problem is that loops are not synchronized. Specially when I switch to "Pressure 3.8 Bar" state during cycle running control loop (second while) is still working based on "Pressure 2 Bar" state not 3.8 bar. Because of this motor pressure goes to 3.8 bar for a sec (becuase of  "Pressure 3.8 Bar" state) and comes back to 2 bar (because the second while still has not gotten that new state,most probably cause of all the delays in the loop)  and after couple seconds it goes back to 3.8 bar.
    I really don’t know what to do. Is there a way to fix this? Or I should consider a better way to do this?
    I went through Occurrence Palette but couldnt figure out how to embed that in the VI. 
    Sorry for my poor English. I attached VI and it's subVIs as a LLB file. I can explain more details if somebody wants. 
    Attachments:
    QuickStartCycle.llb ‏197 KB

    I make it a point to NEVER have a WAIT function inside a state machine.
    It sort of defeats the purpose, which I define as "Examine current state; decide whether you've met the conditions to advance to another state, then get out".
    For example, I have a single state machine VI controlling four identical instruments, via TCP connections.
    For some functions, that means issuing a command, waiting 60 seconds, then reading results.
    If I waited INSIDE the state machine, then it's tied up waiting on one device and cannot handle any others.
    Not a good plan.
    To handle this, I have a loop which calls the state machine.  After issuing the command, the state goes to "Waiting on Response", and there is a target time of 60 seconds from now.
    It's called over and over in that state, and each time merely compares NOW to the target time.  If NOW is past the target, then we read the results.
    the state machine can tell the caller when to call back; that's how I distinguish between an urgent need and nothing-to-do.
    By having the CALLER do the waiting, instead of the state machine itself, the state machine is free to handle another device, or do something else on the same device.
    You should be calling the state machine over and over and over anyway.  So, have the state machine "control the pressure" on every call, and THEN examine whatever state it's in.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Try catch problem in a while loop

    I have computerGuess set to -1 and that starts the while loop.
    but I need to catch exceptions that the user doesnt enter a string or anything other than a number between 1 and 1000.
    but computerGuess is an int so that the while loop will start and I wanted to reset computerGuess from the user input using nextInt().
    The problem is if I want to catch exceptions I have to take a string and parse it.
    import java.util.Scanner;
    public class Game {
         //initiate variables
         String computerStart = "yes";
         String correct = "correct";
         String playerStart = "no";
         int computerGuess = 500;
    public void Start()
         //setup scanner
         Scanner input = new Scanner(System.in);
         int number = (int)(Math.random()*1001);
         System.out.println(welcome());
         String firstAnswer = input.nextLine();
         if(firstAnswer.equalsIgnoreCase(computerStart)== true)
              System.out.println(computerGuess());
              //while (userAnswer.equalsIgnoreCase(correct) == false){
                   System.out.println();
         if(firstAnswer.equalsIgnoreCase(playerStart) == true)
              long startTime = System.currentTimeMillis();
              int currentGuess = -1;
              while (currentGuess != number){
              System.out.println(playerGuess());
              String guess = input.next();
              //currentGuess = Integer.parseInt(guess);
              if (currentGuess < number)
                   System.out.println("too low");
              if (currentGuess > number)
                   System.out.println("too high");
              if (currentGuess == number)
                   long endTime = System.currentTimeMillis();
                   System.out.println("Well done, the number is " + number);
              int i = -1;
              try {
                i = Integer.parseInt(guess);
                   } catch (NumberFormatException nfe) {
                        //System.out.println("Incorrect input, please try again.");
              if ( i < 0 || i > 1000 ) {
                   System.out.println("Incorrect input, please try again.");
         private String computerGuess()
               String comGuess = ("The computer will guess your number.\n" +
                        "Please enter \"too high\", \"too low\" or \"correct\" accordingly.");
               return comGuess;
         private String welcome()
              String gameWelcome = "Welcome to the guessing game \n" +
                                        "The objective is to guess a number between 1 and 1000.\n" +
                                        "You can guess the computer's number or it can guess your's.\n" +
                                        "You may enter \"quit\" at any time to exit.\n" +
                                        "Would you like the computer to do the guessing?";
              return gameWelcome;
         private String playerGuess()
              String playerWillGuess = "Guess a number between 1 and 1000.";
              return playerWillGuess;
    }The catch works , but because computerGuess is int -1 so that the while loop will run, I cannot use the input to change computerGuess because it is a string.

    the i was a mistake. and i commented on the other code, because it wasnt working at that moment. I need help understanding the try catch method.
    I want to catch any input that isn't an integer , and I would also like to catch any input that isn't a string at other parts of my program.

  • Probably simple problem with while loops

    I was programming something for a CS class and came across a problem I can't explain with while loops. The condition for the loop is true, but the loop doesn't continue; it terminates after executing once. The actual program was bigger than this, but I isolated my problem to a short loop:
    import java.util.Scanner;
    public class ok {
    public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         String antlol = "p";
         while(antlol == "p" || antlol == "P"){
              System.out.println("write a P so we can get this over with");
              antlol = scan.nextLine(); 
    //it terminates after this, even if I type "P", which should make the while condition true.
    }

    Thanks, that worked.
    I think my real problem with this program was my CS
    teacher, who never covered how to compare strings,Here's something important.
    This isn't just about comparing Strings. This applies to comparing ANY objects. When you use == that compares to see if two references refer to the same instance. equals compares objects for equality in the sense that equality means they have equal "content" as it were.

  • Problem with while loop in thread: starting an audiostream

    Hello guys,
    I'm doing this project for school and I'm trying to make a simple app that plays a number of samples and forms a beat, baed on which buttons on the screen are pressed, think like fruity loops. But perhaps a screenshot of my unfnished GUI makes things a bit more clear:
    [http://www.speedyshare.com/794260193.html]
    Anyway, on pressing the play button, I start building an arraylist with all the selected samples and start playing them. Once the end of the "screen" is reached it should start playing again, this is the while loop:
    public void run(){
            //System.out.println("Wavfiles.size =" + getWavfiles().size());
            System.out.println(repeatperiod);
            if (getWavfiles() == null) {
                System.out.println("Error: list of Wavfiles is empty, cannot start playing.");
            else{
                if(!active) return;
                while(active){
                    System.out.println("Wavfiles.size =" + getWavfiles().size());
                    for (int i=0; i<getWavfiles().size(); i++){
                        Wavplayer filePlayer = new Wavplayer(getWavfiles().get(i).getStream());
                        Timer timer = new Timer();
                        //timer.scheduleAtFixedRate(filePlayer, getWavfiles().get(i).getStartTime(),repeatperiod);
                        timer.schedule(filePlayer, getWavfiles().get(i).getStartTime());
                    try {
                        Thread.sleep(repeatperiod);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(LineBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }But once the second iteration should begin, I'm getting nullpointerexceptions. These nullpointerexceptions come exactly when the second period starts so I suppose the sleep works :-) The nullpointerexception comes from the wavfile I try to play. Wavfile class:
    package BeatMixer.audio;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.TimerTask;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.UnsupportedAudioFileException;
    public class Wavplayer extends TimerTask {
            private SourceDataLine auline;
            private AudioInputStream audioInputStream;
         private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
         public Wavplayer(ByteArrayInputStream wavstream) {
              try {
                   audioInputStream = AudioSystem.getAudioInputStream(wavstream);
              } catch (UnsupportedAudioFileException e1) {
                   e1.printStackTrace();
                   return;
              } catch (IOException e1) {
                   e1.printStackTrace();
                   return;
                    AudioFormat format = audioInputStream.getFormat();
              DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                    try {
                   auline = (SourceDataLine) AudioSystem.getLine(info);
                   auline.open(format);
              } catch (LineUnavailableException e) {
                   e.printStackTrace();
                   return;
              } catch (Exception e) {
                   e.printStackTrace();
                   return;
        @Override
         public void run() {
                    System.out.println(auline);
              auline.start();
              int nBytesRead = 0;
              byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
              try {
                   while (nBytesRead != -1) {
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                        if (nBytesRead >= 0)
                             auline.write(abData, 0, nBytesRead);
              } catch (IOException e) {
                   e.printStackTrace();
                   return;
              } finally {
                   auline.drain();
                   auline.close();
    }auline is null on second iteration, in fact, getAudioInputStream doesn't really work anymore, and I don't know why because I don't change anything about my list of wavfiles as far as I know... Any thoughts or extra info needed?
    Edited by: Lorre on May 26, 2008 12:22 PM

    Is my question not clear enough? Do you need more info? Or is nobody here familiar with javax.sound.sampled?
    Edited by: Lorre on May 26, 2008 2:07 PM

Maybe you are looking for

  • Why do Apps on my iPhone show updates but when I check there are no updates?

    Why do Apps on my iPhone show updates but when I check there are no updates? I check my Apps on my MacBook and it says there is 1 update but when I check that there are none. Then I sync my iPhone with my MacBook and my iPhone says there are 7 update

  • IPhoto on Time Capsule won't open

    When I am connected to my network at home (Time Capsule) and try to open iPhoto it freezes, I get the spinning wheel of death and have to force quit. It does not happen when connected to other networks. Anyone else having this issue. I have been to A

  • How to include .xml on .war generated by jwsc?

    Hello there! When i build my web service i cannot be able to put in the war file my .xml files they are copy out of the war :__ I need those files because are for ibatis This is my build.xml <target name="build.WebService">      <jwsc      srcdir="${

  • FInvoice How to add the SOAP frame thru XSLT transform

    Dear All, i have the following problem i have implemented as xslt codeto send data from SAP Idoc invoic to WS Finvoic . the coding looking as following : <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.or

  • Add review enabled and enforce single service requisitions

    Is there a way/option to make "Add review enabled" for the service, but not allow adding additional services to the requisition once Add & Review Order is clicked? Reason being there may be services that should not be ordered together with other serv