Exceptions in a WHILE loop

Hi ,
I want to do something like this
While Condition
LOOP
BEGIN
Insert into table1 values(......);
Insert into table2 values(......);
Insert into table3 values(......);
Insert into table4 values(......);
Insert into table5 values(......);
Insert into table6 values(......);
condition := FALSE
EXCEPTION
When OTHERS THEN
<capture the error while inserting into an Error table>
END;
END LOOP;
Now I want that If one of the insert statement within the loop fails (say table2)
the exception should be captured and next insert statement (table3) should be
executed.
How can I do this ? I guess I wont even need a loop can any one help
Thanks

I was just going to give an example like that, which I will post below.
@OP: I am not advocating that this is the best way to do this, but I thought you might like an example that you can maybe use for learning or testing things out. Below is an example of putting each insert in its own begin-end block so that the exception can be handled and processing can continue.
create table foo (foo_id number primary key, column2 varchar2(50));
create table error_tbl (dt_tm date default sysdate, err_msg varchar2(2000));
insert into foo (foo_id, column2) values (2, 'data');  --pre-populated so that insert #2 will fail
insert into foo (foo_id, column2) values (4, 'data');  --pre-populated so that insert #4 will fail
commit;
declare
  v_err varchar2(1000);
  procedure insert_stuff(p_id in number, p_col2 in varchar2) is
  begin
    insert into foo (foo_id, column2) values (p_id, p_col2);
  exception when others then
    v_err := substr(SQLERRM,1,1000);
    insert into error_tbl (err_msg)
    values ('Error on id: '||to_char(p_id)||' column2: '||p_col2||' '||v_err);
  end insert_stuff;
begin
  for i in 1..5 loop
    insert_stuff(i,'new stuff');
  end loop;
  commit;
end;
select * from foo;
FOO_ID     COLUMN2
2           data
4           data
1           new stuff
3           new stuff
5           new stuff
select * from error_tbl;
DT_TM                       ERR_MSG
7/20/2012 3:09:15 PM       Error on id: 2 column2: new stuff ORA-00001: unique constraint (AMARTIN.SYS_C0049104) violated
7/20/2012 3:09:15 PM       Error on id: 4 column2: new stuff ORA-00001: unique constraint (AMARTIN.SYS_C0049104) violatedInserts 1, 3, and 5 succeeded, but inserts 2 and 4 failed due to the primary key constraint. Processing in the loop continued despite the error.
There are concerns with running code this way, some of which have already been brought up, but you may find this useful nonetheless.

Similar Messages

  • Can't break out of a while loop

    Hi, I am doing a networking course, for which an assignment was to write an echo client and server. I did the assignment in Java and it works just fine. However, there is something I don't understand that is bugging me. I wanted a way to stop the server by either detecting when the client entered "quit" or when the user of the server entered "quit". This was not part of the assignment, but after trying many different things I really want to know (1) what I am doing wrong and (2) what the correct way to do things would be.
    I tried to put an "if" clause within the while loop so that if the client entered "quit" the server would detect that, close the socket connections, and break the while loop. But... it seems that I have done this wrong and I am not sure why.
    (Note - I am not a Java programer - just a beginner, and the course in question isn't a programming course. I did the program below by following some brief guidelines/tutorial. I don't even have any books on Java to consult right now - just ordered few from Amazon for any future projects.)
    The code:
    // EchoServer.java     - a simple server program. It listens on a predetermined port for an incoming connection.
    //                After a client connects they can input a line of text and
    //                the server will echo the exact same line back.
    import java.io.*;
    import java.net.*;
    public class EchoServer {
         protected static int DEFAULT_PORT = 3004;
         public static void main (String args[]) throws Exception {
              int portNumber;          
              try {
                   portNumber = Integer.parseInt(args[0]);
              } catch (Exception e) {
                   portNumber = DEFAULT_PORT;
              ServerSocket myServer = null;
                try{
                   myServer = new ServerSocket(portNumber);      
                   System.out.println("Echo Server started. Listening on port " + portNumber);
              } catch (IOException e) {
                   System.out.println("Could not listen on port: " + portNumber);
                   System.out.println(e);
              Socket clientSocket = null;                         
              try{          
                     clientSocket = myServer.accept();
              } catch (IOException e) {
                     System.out.println("Accept failed:  " + portNumber);
                   System.out.println(e);
              BufferedReader input = null;     
              PrintWriter output = null;
              try {               
                   input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                   output = new PrintWriter(clientSocket.getOutputStream(), true);
              } catch (IOException e) {
                   System.out.println(e);
              String theLine;     
              while(true){
                   theLine = input.readLine();
                   output.println(theLine);     
                   output.flush();
                        if (theLine.equals("quit"))  {
                             input.close();
                             output.close();
                             clientSocket.close();
                             myServer.close();     
                             break;
                        }     // end if
              }     // end while     
         }     // end main
    }          // end EchoClient

    A few observations:
    - You might as well exit after you have caught your exceptions, since none of the conditions I see would allow your program to run properly afterwards. You can either do that by a System.exit(int) or a return;
    - Although this s an example program, you should take advantage of doing things right. Addining a try-finally would be good for tidying things up. First declare your variables before the main try, otherwise the finally won't be able to do its job. For example (this won't compile as is):
    Socket clientSocket = null;
    ServerSocket myServer = null;
    InputStream in = null;
    OutputStream out =null;
    try {
      String theLine = null;     
      while( (theLine = input.readLine()) != null ){
        output.println(theLine);     
        output.flush();
        if (theLine.equals("quit"))  {
           break;
      }     // end while
    } catch ( IOException ex ) {
      ex.printStackTrace();
    } finally {
      if ( in != null ) {
         in.close();
      if ( out != null ) {
         out.close();
      // add other conditions to close other closeable objects
    }The reasoning is that if an exception were ever to happen you would be sure that the clean up would be done. In your current example you may risk having an inputstream left open. Also note that BufferedReader.readLine() returns null when its arrived at the end of its content.

  • Shift register versus comparison in while loop

    Hello,
    I have a question regarding the "proper" (i.e. cheaper in terms of system ressources, easier to read, etc)  way of testing the first entry in while loop. One way would be by using a shift register another by detecting if the loop iteration is zero (see the exemples attached here).   I am doing some calculations in this loop, typically 300 iterations or so.
    Which way is better ? Are there other (simpler) waysofdoing this ?
    Thanks
    N
    Attachments:
    while_loop1.png ‏54 KB
    while_loop2.png ‏53 KB

    Express vi's are not entirely evil. And the time delay express vi's are harmless. I have found express vi's to be very useful if I'm trying something new. Besides, once you get everything working the way you want it to you can always open the front panel and clean out any extraneous code that might slow things down. Once you have done that it will perform just like you wrote it yourself.
    PaulG.
    "I enjoy talking to you. Your mind appeals to me. It resembles my own mind except that you happen to be insane." -- George Orwell

  • 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

  • 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

  • How do I run two while loops independent of each other?

    I have a simple VI. I have loop 1 with and LED and a stop button and I have loop 2 with an LED and stop button.  They are both in while loops.  When I run the VI,if I stop loop 1, I can not turn it back on.  If I stop loop 2, it will not stop.  I've attached a file with my VI.  
    Attachments:
    2 Loops.vi ‏9 KB

    bebesbabe,
    This looks like a learning exercise, so I will not present a complete solution.
    1. It is not polite to post to the Forum a VI which will not stop except by pressing the Abort button.  The Abort button should only be used to stop a VI if something is wrong with the program during development. Add a stop button to the outer loop.
    2. A loop with no delay will try to run as fast as possible, consuming all the CPU resources it can get. Since these loops are for user interfaces, delays of 100 to 200 ms are appropriate. Use the Wait (ms) function.
    3. Your main problem is understanding dataflow. In LabVIEW any node may execute only when all of its inputs have been given data and it will not complete its execution until all nodes inside it have completed.  Your VI does not have external inputs so waiting for data is not a factor. Each loop is considered a node. So the outer loop will iterate only after BOTH of the inner loops have stopped.  On the next iteration both inner loops will be started again.  Of course if the stop buttons are still pressed, the will stop after one iteration, which will seem almost instantaneous. But because of dataflow as I have described, your program cannot really work the way you want. You cannot restart one loop until both have stopped. Put an indicator on the "i" terminal of the outer loop.
    4. You may wish to consider changing the mechanical action on your stop buttons to Latch when Released.  Read the help to learn about mechanical actions.
    The way the instructions on the front panel read, it is not clear what the intended solution is. What control or user action or program action is required to turn the loops back on? Changing the stop button?  Automatically after a delay? A separate On switch?  How is the entire program supposed to stop?
    Lynn

  • Need help on a while loop

    Hi...I am somewhat new to Java and I am trying to do a nested while loop. Basically I have a result set from a query and I want to loop though that result set BUT I need a second loop to put together 150 of the results at a time and add them to a GeoCodeRequest to send to MapInfo.....this is how I think the code should look, I need some advice if it is the proper way to loop through....
    ArrayList aal = new ArrayList();
    ServiceMessage sm = new ServiceMessage();
    ServiceMessage rsm = new ServiceMessage();
    while (rset.next())
    statRecord = statRecord + currentRecord;
    while (rset.next() && currentRecord <= 150)
    AddressEx a = new AddressEx(rset.getString(6));
    ContentColumn cc = new ContentColumn("mmhid");
    cc.setValue(rset.getString(1));
    StreetAddress streetAddress = new StreetAddress(rset.getString(3));
    streetAddress.setBuildingName(rset.getString(2));
    a.setCountrySubdivision(rset.getString(5));
    a.setMunicipality(rset.getString(4));
    a.setPostalCode(rset.getString(6));
    a.setContentColumn(0,cc);
    aal.add(a);
    currentRecord++;
    System.out.println("Inside inner while loop now..");
    System.out.println("Add 150 to request...");
    GeocodeRequestEx gr = new GeocodeRequestEx("","3.0","id",(AddressEx[])aal.toArray());
    gr.setGeocodePreference(pref);
    sm.addRequest(gr);
    System.out.println("going to geocode now...");
    try{
    LocationUtilityServiceLocator lus = new LocationUtilityServiceLocator();
    LocationUtility lu = lus.getLocationUtility(new URL(url));
    XLSType xr = lu.perform(sm.toXLS());
    rsm = new ServiceMessage(xr);......
    code goes on to do oter things but this is the basis..............
    I hope that all made since.....please help.

    I am not sure if there is a problem, that is what I am
    asking......if I have the logic correct.
    I haven't been able to test it correct because I am
    getting an:
    Exception in thread "main"
    java.lang.ClassCastException: [Ljava.lang.Object; at
    geoClient.main(geoClient.java:127)
    That means you don't have it correct.  :-)> on the following line:> > GeocodeRequestEx gr = new> GeocodeRequestEx("","3.0","id",(AddressEx[)aal.toArray
    and I haven't figured out to correct that yet......You need to use toArray(Object[]).

  • Calling web service method.Stuck in while loop

    I am implementing a board game using asp.net web service. Players connect to this web service and play.
    Once player click on a cell in board it should be written to web service and other players board repaint according to that click.Writtting to web and reading is working, but the switch player method in below do not work.It stuck in the while loop.Even other player has played this player do not identify he has played it wait in the loop.
    private void switchPlayer(String player){
            try { // This code block invokes the ServiceSoap:switchPlayer operation on web service
                webservice.Service service = new web.Service_Impl();
                webservice.ServiceSoap serviceSoap = service.getServiceSoap();
                while(serviceSoap.switchPlayer(player)!="aPlayer"){
                   System.out.println("It's oppenents turn");//Stuck here
                    //remote player already exists?
              //   readLabel();
                System.out.println("It's my turn");//don't come here even player b played
                       }  catch(Exception ex) {
                // TODO handle custom exceptions here
              }

    Does some one knows url of similar type game
    designing.I would suggest that you get your basics right before going into that stuff.

  • Stop/ abort execution in case when the task inside while loop can not be completed

    I am using Count digital events example from LabVew. This VI is using DAQmx Read vi. If I press Stop button before this DAQ gets required amount of samples VI does not stop. I tried to change amount of samples on a fly with stop button but it did not work either.
    Please help.

    This is directly related to the way LV handle the data. Your question is similar to "How can I stop a For-Next loop before completion ?". The answer is : No way, except changing the loop for a while loop (ie: change the algorithm) or stop the whole vi.
    Attached is an example of stopping an infinite running loop. It uses a parallel loop, with a Stop node (see how to handle the stop button in order to reset it to false at the next vi run).
    If you only want to stop the DAQ, whithout halting everything else, the solution is trickier : you will have to run your DAQ loop in a dynamically loaded vi, then use the vi server functions to halt the vi if the run period is excessive. But that is worth another discussion...
    Give some feedback !..
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Stop_infinite_loop.vi.zip ‏9 KB

  • 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...

  • Event Structures and Do /While Loops

    I have an Event Structure inside a Do/While Loop.  One of the buttons in the event is STOP which stops the do while.  The Stop Button itself is inside the event as suggested in the help.  My problem is when I hit the stop button everything inside the Do/While runs 1 more time.  Other than than the code works perfectly.  is this normal behavior for a Do/While ..Event Structure??

    The attached file is the code in a nutshell.  I know it can sometimes be diffcult to TS w/o the actual code.  Prob is I wrote it in LV2011 on the Lab PC and I have LV2010 at my desk.  I don't have internet access in the Lab..of course.
    If I hit the OK button 2x's it "does something...does something...build array" then again a second time.  The build array is added to with each click of a button in the event structure.  If the user hits the STOP it dumps the 2x's worth of data out to excel..except I get 3 rows of data rather than 2...as if the inner loop ran one more time.
    Anyways. the only thing that caught my eye is the fact that I don't have a sequence structure around the "build data here" portion of the code.  Would that affect how the STOP inside the do while loop is handled??
    Attachments:
    event_Do_While.JPG ‏90 KB

  • How I break while loop activity in BPEL process

    Hi Guys,
    I want to do a polling action in my bpel process, I put in the polling code in while activity ,
    I try two way to do the break :
    1. use the Flow activity , one sequence for while loop activity , one sequence for timeout flow , put waiting activity in it ,config timeout ... but Flow activity complete only when all branch complete . so it seems there is no way to break Flow from one branch.
    2.use onalarm branch of scope ... put while activity code in a scope activity , create onalarm branch for this scope ,config the timeout time ... but onalarm branch can't bypass the scope sequence...
    Any advice ?
    Thanks
    Kevin
    Edited by: kyi on Oct 29, 2009 1:01 PM

    The on-alarm branch of the scope should work.
    Maybe not so neat but you could try to do a scope with a flow within that. Put in one of the flow-branches a wait. After the wait throw an exception.
    You can catch that exception in a catch branch of the surrounding scope.
    Regards,
    Martien

  • While loop not performing correctly

    When I enter ANY number, the second while loop in the code below executes. It should not execute when 117, 239, 298, 326, or 445 is entered. I can't seem to figure out why this does not work, and I do not know what else to try.
    Hope someone can just give some assistance. Thank you!
    If I need to supply the entire program, just let me know.
    while(! done)
                   try
                        System.out.println("Enter the flight number");
                        entry = keyboard.nextInt();
                        while((entry != 117) || (entry != 239) || (entry != 298) || (entry != 326) || (entry!= 445))
                             System.out.println("Flight number must be 117, 239, 298, 326, 445");
                             System.out.println("Please try again");
                             entry = keyboard.nextInt( );
                             done = true;
                   catch(InputMismatchException e)
                        keyboard.nextLine();
                        System.out.println("Not the correct entry");
                        System.out.println("Please try again");
              }

    JosAH wrote:
    paulcw wrote:
    The outer loop loops on "not done", but in the body of that loop, done is unconditionally set to true. So the outer loop will only run once. Therefore it's pointless. I'm guessing that you meant to only set done to true if the user inputs "quit" or something.The 'not done' loop will iterate again if the user supplied incorrect input (not an int).Man that's a confusing flow of control. So if the user types in anything other than a number, it's causes a parse error (basically) and the exception causes it to skip the command to stop, and that makes it loop again.
    So apparently 3/4 of the people looking at that code didn't get it at first.
    It reminds me of the veda about Mel.
    Come up with something clearer.

  • Coherence averaging without while loop

    Hi all,
    I attached a VI (Coherence.vi using LabVIEW 2011) that calculates and plots the coherence for two simulated signals. It works fine but I want to make a change that I don't know how to manage.
    I want to elimnate the while loop (as I am planning to convert this VI into dll and use it in JAVA appilcation) and do the averaging in an alternative way without using while or for loop.
    The problem with the while/for loop is that the dll doesn't give any output except if the while/for loop is stopped.
    Is there any ideas?
    Attachments:
    Coherence.vi ‏24 KB

    Hi Cowboy12,
    From what I understand, it looks like the averaging VI in your code uses uninitialized shift registers to store previous data, similar to functional global variables.  It seems that each time you are calling this VI from java the result exits out of LabVIEW memory after executing.  This means that each time you call the VI from java you are getting a new instance of it with no memory of the previously averaged signal.
    I think your best bet is to keep the while loop in LabVIEW, so that the current averaging VI works appropriately.  If you really must remove the while loop, then you could write your own version of the averaging VI that takes in the last averaged signal and feeds it into the currently uninitialized shift register.  You would then also need some way of storing this averaged signal in Java and then sending it back into LabVIEW the next time you call the VI.  However, this seems like a very complicated way to obtain the result you want.
    Hope this helps!
    Lindsey W. | Applications Engineer | National Instruments

  • FUNCTION Cursor / WHILE LOOP vs LOOP / Logic help (RESOLVED)

    (I HAVE RESOLVED - making it more efficient, I hope - see FUNCTION) if anyone has a different =, more efficient way to write this, please share...
    I need help with a Function:
    I am trying to get a handle on a rate. This table has and employee column this is usually populated with 'ALL'. On the off chance that it has an actual employee number, I want that rate; otherwise, the rate with ALL. Everything in both records will be the same except the employee field. (if there happens to be an ALL rate and an individual employee rate. Usually there will only be one record).
    As I started to write this, I tested the WHILE loop logic and did not get a value back, but when I test a simple loop, I do. I have not finished the entire logic only getting a handle on a record that has the employee.
    I would like help:
    Understanding why WHILE loop isn't working
    How to go about testing if CURSOR c_job_payroll_rate_emp FOUND - get this value and EXIT otherwise IF NOT FOUND then get value from c_job_payroll_rate_all
    Start to my function is below w/ testing comments(** THIS IS THE RESOLVED FUNCTION.
    FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
                        in_job_code IN jobpayrate.jpr_job_code%TYPE,
                             in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
                                  in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
                                  in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
                                  in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
    RETURN jobpayrate.jpr_billing_rate%TYPE
    IS
    v_val jobpayrate.jpr_billing_rate%TYPE;
    CURSOR c_job_payroll_rate_all IS     
         SELECT max(jpr_billing_rate) rate
         FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
         AND jpr_job_code = in_job_code
         AND jpr_trd_code = in_trd_code      
         AND jpr_phs_code = in_phs_code
         AND jpr_cat_code = in_cat_code
         AND jpr_emp_no <> in_emp_code;     
    CURSOR c_job_payroll_rate_emp IS     
         SELECT max(jpr_billing_rate) rate
         FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
         AND jpr_job_code = in_job_code
         AND jpr_trd_code = in_trd_code
         AND jpr_phs_code = in_phs_code
         AND jpr_cat_code = in_cat_code
         AND jpr_emp_no = in_emp_code;     
    BEGIN
    FOR rec_e IN c_job_payroll_rate_emp LOOP
    v_val := rec_e.rate;
    IF rec_e.rate IS NULL THEN
    FOR rec_a IN c_job_payroll_rate_all LOOP
    v_val := rec_a.rate;
    END LOOP;
    END IF;
    END LOOP;
    RETURN v_val;
    END job_pay_rate;
    Message was edited by:
    KB

    Rather than using cursors for zero or 1 row queries, use SELECT ... INTO
    Untested
    FUNCTION job_pay_rate(in_comp_code IN jobpayrate.jpr_comp_code%TYPE,
    in_job_code IN jobpayrate.jpr_job_code%TYPE,
    in_phs_code IN jobpayrate.jpr_phs_code%TYPE,
    in_cat_code IN jobpayrate.jpr_cat_code%TYPE,
    in_trd_code IN jobpayrate.jpr_trd_code%TYPE,
    in_emp_code IN jobpayrate.jpr_emp_no%TYPE)
    RETURN jobpayrate.jpr_billing_rate%TYPE
    IS
    v_val jobpayrate.jpr_billing_rate%TYPE;
    BEGIN
    SELECT max(jpr_billing_rate) rate INTO v_val
    FROM jobpayrate
    WHERE jpr_comp_code = in_comp_code
    AND jpr_job_code = in_job_code
    AND jpr_trd_code = in_trd_code
    AND jpr_phs_code = in_phs_code
    AND jpr_cat_code = in_cat_code
    AND jpr_emp_no = in_emp_code;
    RETURN v_val;
    EXCEPTION
      WHEN NO_DATA_FOUND THEN
        SELECT max(jpr_billing_rate) rate INTO v_val
        FROM jobpayrate
        WHERE jpr_comp_code = in_comp_code
        AND jpr_job_code = in_job_code
        AND jpr_trd_code = in_trd_code
        AND jpr_phs_code = in_phs_code
        AND jpr_cat_code = in_cat_code
        AND jpr_emp_no <> in_emp_code;
        RETURN v_val;
    --OTHER EXCEPTION HANDLING
    END;

Maybe you are looking for