For loop in a recursion

I am trying to write a program in which a series of numbers are generated by a recursive function based on strict number rules... such as the first number is always 94 and it can be only followed by 94,95,96,97, etc... I would like to get some help because I am doing a for loop in my recursive method, however the method just ends after one iteration and only display the first serie of numbers. I don't understand what I did wrong, so if someone could fix that part for me or tell me what is going wrong, I will appreciate a lot... Here is the code:
public class StringSeries {
     static int nextInteger;
     static int lastInteger;
     static String numberWord = "";
     public static int[] lastNumber(int k, int nextK){
          if (k==94){
               if (nextK==94){
                    int numEnd9494[]={97};
                    return numEnd9494;
               if (nextK==95){
                    int numEnd9495[]={97,98};
                    return numEnd9495;
               if (nextK==96){
                    int numEnd9496[]={97,98,99};
                    return numEnd9496;
               if (nextK==97){
                    int numEnd9497[]={97,98,99};
                    return numEnd9497;
               if (nextK==98){
                    int numEnd9498[]={98,99};
                    return numEnd9498;
               if (nextK==99){
                    int numEnd9499[]={99};
                    return numEnd9499;
          return null;
     public static int[] nextNumber(int n){
          if(n==94){
               int numArray94[] = {94,95,96,97};
               return numArray94;
          if(n==95) {
               int numArray95[] = {95,96,97,98};
               return numArray95;
          if(n==96) {
               int numArray96[] = {96,97,98,99};
               return numArray96;
          if(n==97) {
               int numArray97[] = {97,98,99};
               return numArray97;
          if(n==98){
               int numArray98[] = {98,99};
               return numArray98;
          if(n==99){
               int numArray99[] = {99};
               return numArray99;
          else
               return null;
     // When this method is called out for the first time, "nextInt" must be the same as "firstInt"
     public static String generateSequence(int firstInt, int nextInt, int seqLength){
          if (seqLength==1) {
               for (int i=0; i<(lastNumber(firstInt,nextInt)).length; i++) {
                         lastInteger = (lastNumber(firstInt,nextInt));
                         numberWord = "" + lastInteger;
                         return numberWord;
          else {
                    for (int j=0; j <(nextNumber(nextInt)).length; j++){
                         nextInteger = (nextNumber(nextInt))[j];
                         numberWord = nextInteger + " " + generateSequence(firstInt,nextInteger,seqLength-1);
                         return numberWord;
               return null; //I don't understand why I have to put this line or else I get a compiler error     
     } // End of method
} // End of class

I made that one change, but then I just get the last serie of numbers.... Is there like some small mistake with my for loop besides the one you had pointed out?
// When this method is called out for the first time, "nextInt" must be the same as "firstInt"
     public static String generateSequence(int firstInt, int nextInt, int seqLength){
          if (seqLength==1) {
               for (int i=0; i<(lastNumber(firstInt,nextInt)).length; i++) {
                         lastInteger = (lastNumber(firstInt,nextInt));
                         numberWord = "" + lastInteger;
return numberWord;
          else {
                    for (int j=0; j <(nextNumber(nextInt)).length; j++){
                         nextInteger = (nextNumber(nextInt))[j];
                         numberWord = nextInteger + " " + generateSequence(firstInt,nextInteger,seqLength-1);
return numberWord;
     } // End of method                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • For-loop in XSLT-Important

    All,
    version:11.1.1.4
    I have a requirement in the for-loop which has to iterate for a fixed loop. For instance: I want the for-loop to iterate only for 5 times, how should I define the for-loop?  Any idea, please share your thoughts.
    <xsl:for-each select="5">
    </xsl:for-each>
    I tried the above code, didn't work!.
    Rgds
    sen

    You can use templates in xslt like one below :-  Assign max - 5 and this will loop for 5 times.
    <xsl:template name="loop">
      <!--recursive loop until done-->
      <xsl:param name="i"/>
      <xsl:param name="max"/>
      <xsl:if test="$i &lt;= $max">
        <!-- Repeated content Here -->
        <!-- use value-of i to get loop index -->
        <xsl:value-of select="$i"/>.<br/>
          <xsl:call-template name="loop">
            <xsl:with-param name="i" select="$i + 1"/>
            <xsl:with-param name="max" select="$max"/>
          </xsl:call-template>
      </xsl:if>
    </xsl:template>
    <xsl:call-template name="loop">
      <xsl:with-param name="i" select="number(1)"/>
      <xsl:with-param name="max" select="number(5)"/>
    </xsl:call-template>
    Or you can also do while loop like one below:-
    <!-- recursive named template -->
    <xsl:template name="while">
    <xsl:variable name="VALUE">
    <!-- your evaluation -->
    </xsl:variable>
    <!-- evaluate and recurse -->
    <xsl:if test="$VALUE=0">
       <xsl:call-template name="while"/>
    </xsl:if>
    </xsl:template>

  • Cursor for loop problem

    Hi to all!
    I have this sample data:
    CREATE TABLE person(id NUMBER PRIMARY KEY,
                        first_name VARCHAR2(30),
                        father_id NUMBER REFERENCES person(id),
                        mother_id NUMBER REFERENCES person(id));
    INSERT INTO person
    VALUES (1, 'John', NULL, NULL);
    INSERT INTO person
    VALUES (10, 'John''s son Bill', 1, NULL);
    INSERT INTO person
    VALUES (20, 'John''s daughter Briana', 1, NULL);
    INSERT INTO person
    VALUES (100, 'Bill''s son George', 10, NULL);
    INSERT INTO person
    VALUES (101, 'Bill''s son Matthew', 10, NULL);
    INSERT INTO person
    VALUES (200, 'Briana''s son Greg', 20, NULL);
    INSERT INTO person
    VALUES (201, 'Briana''s son Fred', 20, NULL);
    /Then I execute this PL/SQL anonymous block:
    SET SERVEROUTPUT ON
    DECLARE
        CURSOR children IS
          SELECT s.first_name name
          FROM person s, person p
          WHERE (s.father_id = p.id OR s.mother_id = p.id)
          AND p.id = 1;
        CURSOR g_children IS
            SELECT s.first_name gc_name
            FROM person s, person p
            WHERE (s.father_id = p.id OR s.mother_id = p.id)
            AND p.id IN (SELECT gs.id FROM person gs, person gp
                         WHERE  (gs.father_id = gp.id OR gs.mother_id = gp.id)
                         AND gp.id = 1);      
    BEGIN
        FOR c_rec IN children LOOP
          DBMS_OUTPUT.PUT_LINE(c_rec.name);
             FOR g_rec IN g_children LOOP
                DBMS_OUTPUT.PUT_LINE(g_rec.gc_name);
             END LOOP;
        END LOOP;
    END;I have this result:
    John's son Bill
    Bill's son George
    Bill's son Matthew
    Briana's son Greg
    Briana's son Fred
    John's daughter Briana
    Bill's son George
    Bill's son Matthew
    Briana's son Greg
    Briana's son FredHow could I modify nested for loop, so that I have output like this:
    John's son Bill
    Bill's son George
    Bill's son Matthew
    John's daughter Briana
    Briana's son Greg
    Briana's son FredSo that I have one child and then his children, and then second child and his/her children, and so on.
    Thanks!
    Edited by: Spooky on 2013.02.06 12:54

    Suri wrote:
    BluShadow wrote:
    You would need to parameterize your children query to it only get's the children of that parent.Hi Blu,
    I understood that it can be easily solved by CONNECT BY PRIOR clause.
    Just for curisosity I am asking you, Assume that if we dont know till what level children details exist in person table (for eg: John's son is Bill , Bill's son is XYZ , XYZ son is ABC etc), is there any better way to acheive this using parameter cursor. Oh yeah, sure... use recursion...
    SQL> CREATE TABLE person(id NUMBER PRIMARY KEY,
      2                      first_name VARCHAR2(30),
      3                      father_id NUMBER REFERENCES person(id),
      4                      mother_id NUMBER REFERENCES person(id)
      5                     )
      6  /
    Table created.
    SQL>
    SQL> INSERT INTO person VALUES (1, 'John', NULL, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (10, 'John''s son Bill', 1, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (20, 'John''s daughter Briana', 1, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (100, 'Bill''s son George', 10, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (101, 'Bill''s son Matthew', 10, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (200, 'Briana''s son Greg', 20, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (201, 'Briana''s son Fred', 20, NULL);
    1 row created.
    SQL>
    SQL> set serverout on
    SQL>
    SQL> declare
      2    procedure recurse_persons(father_id in number, lvl number := 0) as
      3      cursor cur_person is
      4        select *
      5        from   person
      6        where  nvl(father_id,0) = nvl(recurse_persons.father_id,0);
      7    begin
      8      for p in cur_person
      9      loop
    10        dbms_output.put_line('['||to_char(lvl+1)||']'||lpad(' ',lvl*2,' ')||p.first_name);
    11        recurse_persons(p.id, lvl+1);
    12      end loop;
    13    end;
    14  begin
    15    recurse_persons(null);
    16  end;
    17  /
    [1]John
    [2]  John's son Bill
    [3]    Bill's son George
    [3]    Bill's son Matthew
    [2]  John's daughter Briana
    [3]    Briana's son Greg
    [3]    Briana's son Fred
    PL/SQL procedure successfully completed.With that, we're just using one cursor definition that suits all, and using recursion to go down each branch of the hierarchy, regardless of how deep. Of course you then run the risk (if it's a very deep hierarchy) of getting a "too many open cursors" error.

  • How can I repeat a for loop, once it's terms has been fulfilled???

    Well.. I've posted 2 different exceptions about this game today, but I managed to fix them all by myself, but now I'm facing another problem, which is NOT an error, but just a regular question.. HOW CAN I REPEAT A FOR LOOP ONCE IT HAS FULFILLED IT'S TERMS OF RUNNING?!
    I've been trying many different things, AND, the 'continue' statement too, and I honestly think that what it takes IS a continue statement, BUT I don't know how to use it so that it does what I want it too.. -.-'
    Anyway.. Enought chit-chat. I have a nice functional game running that maximum allows 3 apples in the air in the same time.. But now my question is: How can I make it create 3 more appels once the 3 first onces has either been catched or fallen out the screen..?
    Here's my COMPLETE sourcecode, so if you know just a little bit of Java you should be able to figure it out, and hopefully you'll be able to tell me what to do now, to make it repeat my for loop:
    Main.java:
    import java.applet.*;
    import java.awt.*;
    @SuppressWarnings("serial")
    public class Main extends Applet implements Runnable
         private Image buffering_image;
         private Graphics buffering_graphics;
         private int max_apples = 3;
         private int score = 0;
         private GameObject player;
         private GameObject[] apple = new GameObject[max_apples];
         private boolean move_left = false;
         private boolean move_right = false;
        public void init()
            load_content();
            setBackground(Color.BLACK);
         public void run()
              while(true)
                   if(move_left)
                        player.player_x -= player.movement_speed;
                   else if(move_right)
                        player.player_x += player.movement_speed;
                   for(int i = 0; i < max_apples; i++)
                       apple.apple_y += apple[i].falling_speed;
                   repaint();
                   prevent();
                   collision();
              try
              Thread.sleep(20);
              catch(InterruptedException ie)
              System.out.println(ie);
         private void prevent()
              if(player.player_x <= 0)
              player.player_x = 0;     
              else if(player.player_x >= 925)
              player.player_x = 925;     
         private void load_content()
         MediaTracker media = new MediaTracker(this);
         player = new GameObject(getImage(getCodeBase(), "Sprites/player.gif"));
         media.addImage(player.sprite, 0);
         for(int i = 0; i < max_apples; i++)
         apple[i] = new GameObject(getImage(getCodeBase(), "Sprites/apple.jpg"));
         try
         media.waitForAll();     
         catch(Exception e)
              System.out.println(e);
         public boolean collision()
              for(int i = 0; i < max_apples; i++)
              Rectangle apple_rect = new Rectangle(apple[i].apple_x, apple[i].apple_y,
    apple[i].sprite.getWidth(this),
    apple[i].sprite.getHeight(this));
              Rectangle player_rect = new Rectangle(player.player_x, player.player_y,
    player.sprite.getWidth(this),
    player.sprite.getHeight(this));
              if(apple_rect.intersects(player_rect))
                   if(apple[i].alive)
                   score++;
                   apple[i].alive = false;
                   if(!apple[i].alive)
                   apple[i].alive = false;     
         return true;
    public void update(Graphics g)
    if(buffering_image == null)
    buffering_image = createImage(getSize().width, getSize().height);
    buffering_graphics = buffering_image.getGraphics();
    buffering_graphics.setColor(getBackground());
    buffering_graphics.fillRect(0, 0, getSize().width, getSize().height);
    buffering_graphics.setColor(getForeground());
    paint(buffering_graphics);
    g.drawImage(buffering_image, 0, 0, this);
    public boolean keyDown(Event e, int i)
         i = e.key;
    if(i == 1006)
    move_left = true;
    else if(i == 1007)
         move_right = true;
              return true;     
    public boolean keyUp(Event e, int i)
         i = e.key;
    if(i == 1006)
    move_left = false;
    else if(i == 1007)
         move_right = false;
    return true;
    public void paint(Graphics g)
    g.drawImage(player.sprite, player.player_x, player.player_y, this);
    for(int i = 0; i < max_apples; i++)
         if(apple[i].alive)
              g.drawImage(apple[i].sprite, apple[i].apple_x, apple[i].apple_y, this);
    g.setColor(Color.RED);
    g.drawString("Score: " + score, 425, 100);
    public void start()
    Thread thread = new Thread(this);
    thread.start();
    @SuppressWarnings("deprecation")
         public void stop()
         Thread thread = new Thread(this);
    thread.stop();
    GameObject.java:import java.awt.*;
    import java.util.*;
    public class GameObject
    public Image sprite;
    public Random random = new Random();
    public int player_x;
    public int player_y;
    public int movement_speed = 15;
    public int falling_speed;
    public int apple_x;
    public int apple_y;
    public boolean alive;
    public GameObject(Image loaded_image)
         player_x = 425;
         player_y = 725;
         sprite = loaded_image;
         falling_speed = random.nextInt(10) + 1;
         apple_x = random.nextInt(920) + 1;
         apple_y = random.nextInt(100) + 1;
         alive = true;
    And now all I need is you to answer my question! =)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    package forums;
    import java.util.Random;
    import javax.swing.Timer;
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class VimsiesRetardedAppleGamePanel extends JPanel implements KeyListener
      private static final long serialVersionUID = 1L;
      private static final int WIDTH = 800;
      private static final int HEIGHT = 600;
      private static final int MAX_APPLES = 3;
      private static final Random RANDOM = new Random();
      private int score = 0;
      private Player player;
      private Apple[] apples = new Apple[MAX_APPLES];
      private boolean moveLeft = false;
      private boolean moveRight = false;
      abstract class Sprite
        public final Image image;
        public int x;
        public int y;
        public boolean isAlive = true;
        public Sprite(String imageFilename, int x, int y) {
          try {
            this.image = ImageIO.read(new File(imageFilename));
          } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Bailing out: Can't load images!");
          this.x = x;
          this.y = y;
          this.isAlive = true;
        public Rectangle getRectangle() {
          return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
      class Player extends Sprite
        public static final int SPEED = 15;
        public Player() {
          super("C:/Java/home/src/images/player.jpg", WIDTH/2, 0);
          y = HEIGHT-image.getHeight(null)-30;
      class Apple extends Sprite
        public int fallingSpeed;
        public Apple() {
          super("C:/Java/home/src/images/apple.jpg", 0, 0);
          reset();
        public void reset() {
          this.x = RANDOM.nextInt(WIDTH-image.getWidth(null));
          this.y = RANDOM.nextInt(300);
          this.fallingSpeed = RANDOM.nextInt(8) + 3;
          this.isAlive = true;
      private final Timer timer = new Timer(200,
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            repaint();
      public VimsiesRetardedAppleGamePanel() {
        this.player = new Player();
        for(int i=0; i<MAX_APPLES; i++) {
          apples[i] = new Apple();
        setBackground(Color.BLACK);
        setFocusable(true); // required to generate key listener events.
        addKeyListener(this);
        timer.setInitialDelay(1000);
        timer.start();
      public void keyPressed(KeyEvent e)  {
        if (e.getKeyCode() == e.VK_LEFT) {
          moveLeft = true;
          moveRight = false;
        } else if (e.getKeyCode() == e.VK_RIGHT) {
          moveRight = true;
          moveLeft = false;
      public void keyReleased(KeyEvent e) {
        moveRight = false;
        moveLeft = false;
      public void keyTyped(KeyEvent e) {
        // do nothing
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //System.err.println("DEBUG: moveLeft="+moveLeft+", moveRight="+moveRight);
        if ( moveLeft ) {
          player.x -= player.SPEED;
          if (player.x < 0) {
            player.x = 0;
        } else if ( moveRight ) {
          player.x += player.SPEED;
          if (player.x > getWidth()) {
            player.x = getWidth();
        //System.err.println("DEBUG: player.x="+player.x);
        Rectangle playerRect = player.getRectangle();
        for ( Apple apple : apples ) {
          apple.y += apple.fallingSpeed;
          Rectangle appleRect = apple.getRectangle();
          if ( appleRect.intersects(playerRect) ) {
            if ( apple.isAlive ) {
              score++;
              apple.isAlive = false;
        g.drawImage(player.image, player.x, player.y, this);
        for( Apple apple : apples ) {
          if ( apple.isAlive ) {
            g.drawImage(apple.image, apple.x, apple.y, this);
        g.setColor(Color.RED);
        g.drawString("Score: " + score, WIDTH/2-30, 10);
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("Vimsies Retarded Apple Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new VimsiesRetardedAppleGamePanel());
        frame.pack();
        frame.setSize(WIDTH, HEIGHT);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              createAndShowGUI();
    }Hey Vimsie, try resetting a dead apple and see what happens.

  • Getting the label of a JButton in a for loop

    hi,
    I doing a project for my course at the minute and im in need of a bit of help. I have set up 1-d array of buttons and i have layed them out using a for loop. I have also added an annoymous action listener to each button in the loop. It looks something lke this:
    b = new JButton[43];
    for (int i=1; i<43; i++)
    b[i] = new JButton(" ");
    b.addActionListener(
    new ActionListener()
    public void actionPerformed(ActionEvent e)
              System.out.println("..........");
    }); // addActionListener
    } // for
    I want the "System.out.println( ..." line, to print out the "i" number of the button that was pressed but i cannot figure out how to do it. I cannot put "System.out.println(" "+i);" as it wont recognise i as it is not inside the for loop. Does anyone have any suggestions?
    Thanks!!

    class ButtonExample extends JFrame implements ActionListener{The OP wanted to have anonymous listeners, not a subclassed JFrame
    listening to the buttons. I don't know if the following is the best design,
    since the poster has revealed so little, but here is how to pass the
    loop index to an anonymous class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonExample {
        private JButton[] buttons = new JButton[24];
        public JPanel createGUI() {
            JPanel gui = new JPanel(new GridLayout(6,  4));
            for(int i=0; i<buttons.length; i++) {
                final int ii = i; //!! !
                buttons[i] = new JButton("button #" + i);
                buttons.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    System.out.println("number " + ii);
    gui.add(buttons[i]);
    return gui;
    public static void main(String[] args) {
    ButtonExample app = new ButtonExample();
    JPanel gui = app.createGUI();
    JFrame f = new JFrame("ButtonExample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(gui);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • How to pass the sequence number of current loop in a for loop in FPGA vi to the host

    PCI-7830R
    LV 8.2
    What I was trying to do is to use multiple DIO to generate pulse at different sequence. Mode one is to automatically sweep from DIO1 to DIO20; mode 2 is several DIOs generate pulse simoutaneously.  So I use a case structure to make the selection, in the mean time, I set up two for loop in each case so that I can use multiple pulse generations. For example, in scanning mode, if I set 2 exposures, it sweeps from 1 to 20 then do it again.  
    Then I need to get the loop sequence number, i of each scenario. So I put an indicator within the first loop, and create a local variable of it and put in the second one.  Running the FPGA vi alone, I can see the indicator change in each case from 0 to N-1, N being the for loop time.But in the host vi, I tried to add this indicator as an element in the read/write invoke method, in the debugging mode, I could only see it directly jump to N-1 without all the changes I saw in FPGA vi. 
    Is it possible to get this number passed correctly from FPGA vi to the host vi? Thanks

    Thanks for the reply Jared.
    Excuse me if it looks incorrect, but I'm new to FPGA programming, so I would have to look into the FIFO you referred to.  I used local variables because for one thing I have several different cases containing for loop in each of them, and I only want one indicator for the "i".  If I put the indicator out of any for loop, it's only gonna show the last number which is N-1.  For the other thing, it seems like property nodes are not allowed in FPGA vi.  And by doing this, I can see the i number changing from 0 to N-1 in each case, well, in FPGA vi's front panel.  But while I ran the host vi with everything, the indicator in host vi's front panel only showed the last number N-1. It may be the reason you said, it happened too fast before the indicator in host vi can catch it.
    What I want to realize is to group the data I collect in host vi, for example, when I choose multiple exposure in each mode, and the FPGA runs 1 through 20 then do it again, I want the data stored in two groups using the loop sequence number as the seperator in file name.  So it goes like 1-1, 2-1.......20-1; then 1-2, 2-2,.....20-2.

  • How do we use if statement in labview?moreover can i use if statement inside for loop?

    how do we use if statement in labview?moreover can i use if statement inside for loop?

    The if statement in LabVIEW is the Case structure. You can find that on the Structures palette right next to the For Loop. If you're still on the same subject about terminating a for loop early, then what you do is enclose your functions inside the loop with a case statment and make one of the case's empty except for one or more constants that you might have to wire. Hopefully, the attached picture will explain what I mean. Also, as I mentioned in one of your other posts, I think this technique is not as good as using a while loop. The array in the attached example is the same size no matter what and you may have to handle stripping extra or invalid elements.
    Attachments:
    For_Loop_with_Case.jpg ‏21 KB

  • Select statement in a for loop

    Hi all,
    Can a select stmt be used in the body of the for loop/ nested for loop ?
    I tries using (even if its very simple for loop) it gives the following error
    PL/SQL: ORA-00933: SQL command not properly ended...
    code is
    DECLARE
    CURSOR C1 is select 'Monday'  from dual
    union all
    select 'Tuesday' from dual
    union all
    select 'Wednesday' from dual
    union all
    select 'Thursday' from dual
    union all
    select 'Friday' from dual
    union all
    select 'Saturday' from dual
    union all
    select 'Sunday' from dual;
            type rec_info is record
            name varchar2(20),
            FNAME varchar2(20),
            LNAME varchar2(20)
            type ty_info is table of rec_info;
            info ty_info;
            type rec_abc is record
            day varchar2(3000)
            type ty_abc is table of rec_abc;
            abc ty_abc;
            Cursor C2 is
            select t.name, u.first_name, u.last_name
            from territories t, users u, territories_users tu
            where t.ID = tu.TERRITORY_ID
            and tu.USER_ID = u.ID ;
    BEGIN
    OPEN C1;
    Loop
    FETCH C1 into abc;
    EXIT when C1%notfound;
    DBMS_OUTPUT.PUT_LINE(abc);
    END LOOP;
    CLOSE C1;
    OPEN C2;
    FETCH C2 BULK COLLECT into info;
    CLOSE C2;
           for i in info.first .. info.last
           LOOP
                       for j in abc.first .. abc.last
                       LOOP
                              select --info(i).name, info(i).FNAME, info(i),LNAME,'AM' "AM/PM",
                            to_char(c.name)||' '||ct.PRIMARY_ADDRESS_CITY||','||ct.PRIMARY_ADDRESS_STATE||','||ct.PRIMARY_ADDRESS_COUNTRY
                           from
                            territories t, territories_users tu,
                            users u, calls_users cu, calls c, 
                            calls_contacts cc, contacts ct    
                            where
                            tu.TERRITORY_ID = t.id
                            and t.name = info(i).name
                            and u.first_name = info(i).FNAME
                            and u.last_name = info(i).LNAME
                          and (c.date_start between trim(next_day(sysdate,abc(j).day)) and trim(next_day(sysdate,abc(j).day)))
                            and tu.USER_ID = u.id
                            and cu.USER_ID = u.id
                            and cu.CALL_ID = c.id
                            and to_char(c.time_start,'hh24') < '12'
                            and cc.CALL_ID = c.ID
                            and cc.CONTACT_ID = ct.id
                            and rownum < 2
                     END LOOP;
         END LOOP;
    END;

    "Can a select stmt be used in the body of the for loop/ nested for loop "
    Yes.... but with an INTO part.....
    select c1 , c2 , c3 into var1 , var2 , var3 from table1
    Sim

  • If statement doesn't affect for loop

    I wrote a function within a function to control 2 Tweens.
    (the 2nd one isnt in the function, it's called)
    My problem is... is that it works for the first time.. the button is hovered over and all the other buttons show themselves and then disappear again, except the one you're over. Then I do it a 2nd time and it doesn't work. why is it only working right one time? and why isn't the if statement I put in the local function affecting the for loop? The 2nd time it takes the button you're hovering over with it and fades it out. (even though the if statement registers according to trace)
    this is the code
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    var shortInst:Array = [btn1, btn2, btn3, exit];
    var objTween:Tween;
    function mouseOff(e:Event):void {
         if (e.currentTarget.alpha !== 0) {
              objTween = new Tween(e.currentTarget, "alpha", None.easeOut, 1, 0, 0.25, true);
    var eTimer:Timer = new Timer(3000, 1); //timer that only runs once (in ms)
    function navFX(e:Event):void {
         for (var i:Number = 0; i < shortInst.length; i++) {
              objTween = new Tween(shortInst[i], "alpha", None.easeOut, 0, 1, 0.25, true);
              eTimer.addEventListener(TimerEvent.TIMER, local);
              eTimer.start();
              function local(t:TimerEvent):void {
                   trace("e.target in local func: " + e.target);
                   for (var i:Number = 0; i < shortInst.length; i++) {
                        if (shortInst[i] !== e.target) {
                        shortInst[i].dispatchEvent(new Event(MouseEvent.MOUSE_OUT));

    is this what you want?
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    var shortInst:Array = [btn1,btn2,btn3,exit];
    var objTween:Tween;
    function mouseOff(e:Event):void
    if (e.currentTarget.alpha !== 0)
      objTween = new Tween(e.currentTarget,"alpha",None.easeOut,1,0,0.25,true);
    function navFX(e:Event):void
    var eTimer:Timer = new Timer(3000,1); // <- moved that line here
    for (var i:Number = 0; i < shortInst.length; i++)
      objTween = new Tween(shortInst[i],"alpha",None.easeOut,0,1,0.25,true);
    eTimer.addEventListener(TimerEvent.TIMER, local);
    eTimer.start();
    function local(t:TimerEvent):void
      trace("e.target in local func: " + e.target);
      for (var i:Number = 0; i < shortInst.length; i++)
       if (shortInst[i] !== e.target)
        shortInst[i].dispatchEvent(new Event(MouseEvent.MOUSE_OUT));
    for (var i:Number = 0; i < shortInst.length; i++)
    shortInst[i].alpha = 0;
    shortInst[i].addEventListener(MouseEvent.MOUSE_OVER, navFX);
    shortInst[i].addEventListener(MouseEvent.MOUSE_OUT, mouseOff);

  • Help with Mathscipt and for loop

    I have a code in Mathscript/matlab and I need to output the array out. One option is my first code,the other option is using a for loop, but I am only getting the last ouput out. I need to get the whole output out.
    Any help.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Help with Mathscript_for loop.vi ‏115 KB
    Help with Mathscript_for loop2.vi ‏84 KB

    Here's how it should look like.
    Message Edited by altenbach on 10-30-2008 05:12 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    MathscriptInFOR.png ‏15 KB

  • Why use cursor and for loop?

    Hi All
    So in general why would we use a cursor and a for loop to do update in a stored procedure?
    Why wouldnt we just use a single update statement ?
    is there compelling reason for using a cursor and a for loop: I am reading some code from a co-worker that the business logic for the select (set need to be updated) is complex but the update logic is simple (just set a flag to (0 or 1 or 2 or 3 or 4).
    But eventually the select come down to a key (row_id) so I re-write it using just a single sql statement.
    The size of the main table is about 2.6 to 3million rows
    Any thoughts on that??
    The code below I just do a google for cursor for update example in case for something to play with
    -Thanks for all your input
    create table f (a number, b varchar2(10));
    insert into f values (5,'five');
    insert into f values (6,'six');
    insert into f values (7,'seven');
    insert into f values (8,'eight');
    insert into f values (9,'nine');
    commit;
    create or replace procedure wco as
      cursor c_f is
        select a,b from f where length(b) = 5 for update;
        v_a f.a%type;
        v_b f.b%type;
    begin
      open c_f;
      loop
        fetch c_f into v_a, v_b;
        exit when c_f%notfound;
        update f set a=v_a*v_a where current of c_f;
      end loop;
      close c_f;
    end;
    exec wco;
    select * from f;
    drop table f;
    drop procedure wco;
    Joining multiple tables
    create table numbers_en (
      id_num  number        primary key,
      txt_num varchar2(10)
    insert into numbers_en values (1, 'one'  );
    insert into numbers_en values (2, 'two'  );
    insert into numbers_en values (3, 'three');
    insert into numbers_en values (4, 'four' );
    insert into numbers_en values (5, 'five' );
    insert into numbers_en values (6, 'six'  );
    create table lang (
       id_lang   char(2) primary key,
       txt_lang  varchar2(10)
    insert into lang values ('de', 'german');
    insert into lang values ('fr', 'french');
    insert into lang values ('it', 'italian');
    create table translations (
      id_num    references numbers_en,
      id_lang   references lang,
      txt_trans varchar2(10) not null
    insert into translations values (1, 'de', 'eins'   );
    insert into translations values (1, 'fr', 'un'     );
    insert into translations values (2, 'it', 'duo'    );
    insert into translations values (3, 'de', 'drei'   );
    insert into translations values (3, 'it', 'tre'    );
    insert into translations values (4, 'it', 'quattro');
    insert into translations values (6, 'de', 'sechs'  );
    insert into translations values (6, 'fr', 'six'    );
    declare
      cursor cur is
          select id_num,
                 txt_num,
                 id_lang,
                 txt_lang,
                 txt_trans
            from numbers_en join translations using(id_num)
                       left join lang         using(id_lang)
        for update of translations.txt_trans;
      rec cur%rowtype;
    begin
      for rec in cur loop
        dbms_output.put (
          to_char (rec.id_num         , '999') || ' - ' ||
          rpad    (rec.txt_num        ,   10 ) || ' - ' ||
          rpad(nvl(rec.txt_trans, ' '),   10 ) || ' - ' ||
                   rec.id_lang                 || ' - ' ||
          rpad    (rec.txt_lang       ,   10 )
        if mod(rec.id_num,2) = 0 then
          update translations set txt_trans = upper(txt_trans)
           where current of cur;
           dbms_output.put_line(' updated');
        else
          dbms_output.new_line;
        end if;
      end loop;
    end;
    /Edited by: xwo0owx on Apr 25, 2011 11:23 AM

    Adding my sixpence...
    PL/SQL is not that different from a SQL perspective than any other SQL client language like Java or C# or C/C++. PL/SQL simply integrates the 2 languages a heck of a lot better and far more transparent than the others. But make no mistake in that PL/SQL is also a "client" language from a SQL perspective. The (internal) calls PL/SQL make to the SQL engine, are the same (driver) calls made to the SQL engine when using Java and C and the others.
    So why a cursor and loops in PL/SQL? For the same reason you have cursors and loops in all these other SQL client languages. There are the occasion that you need to pull data from the SQL engine into the local language to perform some very funky and complex processing that is not possible using the SQL language.
    The danger is using client cursor loop processing as the norm - always pulling rows into the client language and crunching it there. This is not very performant. And pretty much impossible to scale. Developers in this case views the SQL language as a mere I/O interface for reading and writing rows. As they would use the standard file I/O read() and write() interface calls.
    Nothing could be further from the truth. SQL is a very advance and sophisticated data processing language. And it will always be faster than having to pull rows to a client language and process them there. However, SQL is not Turing complete. It is not the procedural type language that most other languages we use, are. For that reason there are things that we cannot do in SQL. And that should be the only reason for using the client language, like PL/SQL or the others, to perform row crunching using a client cursor loop.

  • How to add cursor and for loop

    PROCEDURE "TEST" is
    bala number;
    ins1 number;
    ins2 number;
    BEGIN
    select sum(bal) into bala from (select sum(acp.acp_totbal) bal,acp_instruid from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and c_srm_prncplinsid=acp_instruid
    and acp_acntnum!='SG030001'
    group by acp_instruid
    union
    select sum(acp.acp_totbal) bal,acp_instruid from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and acp_acntnum!='SG030001'
    and acp_instruid=c_srm_prntinsid
    group by acp_instruid)view1;
    dbms_output.put_line(bala);
    select acp_instruid into ins1 from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and c_srm_prncplinsid=acp_instruid
    and acp_acntnum='SG030001';
    dbms_output.put_line('principal'||ins1);
    select acp_instruid into ins2 from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and acp_acntnum='SG030001'
    and acp_instruid=c_srm_prntinsid;
    dbms_output.put_line('parent'||ins2);
    update cs_acpos_bkp
    set acp_totbal=-bala
    where acp_instruid=ins2
    and acp_acntnum='SG030001';
    END;
    i have written this code,i need to use cursor and for loops to get more than one rows and update also.
    if there are more than 1 rows in cs_strmap_t,then the procedure throws an error stating that it cannot take 2 rows.
    Edited by: 850836 on Apr 7, 2011 11:43 PM

    PROCEDURE "TEST" is
    bala number;
    ins1 number;
    ins2 number;
    CURSOR cur_1 IS
    select sum(bal) bala from (select sum(acp.acp_totbal) bal,acp_instruid from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and c_srm_prncplinsid=acp_instruid
    and acp_acntnum='SG030001'
    group by acp_instruid
    union
    select sum(acp.acp_totbal) bal,acp_instruid from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and acp_acntnum='SG030001'
    and acp_instruid=c_srm_prntinsid
    group by acp_instruid)view1;
    BEGIN
    select acp_instruid into ins1 from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and c_srm_prncplinsid=acp_instruid
    and acp_acntnum='SG030001';
    dbms_output.put_line('principal'||ins1);
    select acp_instruid into ins2 from cs_strmap_t map,cs_instru_strips strip,cs_acpos_bkp acp
    where c_int_instruid=c_srm_prncplinsid
    and acp_acntnum='SG030001'
    and acp_instruid=c_srm_prntinsid;
    dbms_output.put_line('parent'||ins2);
    for var_for in cur_1
    loop
    update cs_acpos_bkp
    set acp_totbal=var_for.bala
    where acp_instruid=ins2
    and acp_acntnum='SG030001'
    and abs(acp_totbal)>abs(bala);
    dbms_output.put_line(bala);
    end loop;
    END;
    i wrote the following procedure,but the balance is not getting updated.
    Getting this errors when there are more than 1 row in cs_strmap_t table
    ORA-01422: exact fetch returns more than requested number of rows
    ORA-06512: line 22
    ORA-06512: at line 2

  • How to ignore error and continue with next value in PL/SQL FOR loop?

    hi,
    When the DROP INDEX statement fails it have to continue with the next value in FOR loop without exiting from the loop. Can anyone tell me how to do this?
    DECLARE
    CURSOR aud_cur IS
    SELECT key_col_idx FROM audience_work where aud_ref_id between 106 and 109;
    BEGIN
    FOR aud_row IN aud_cur LOOP
    EXECUTE IMMEDIATE
    'DROP INDEX ' || aud_row.key_col_idx;
    END LOOP;
    END;
    Thanks,
    Noble

    DECLARE
      CURSOR aud_cur
      IS
      SELECT key_col_idx FROM audience_work where aud_ref_id between 106 and 109;
    BEGIN
      FOR aud_row IN aud_cur LOOP
        begin
          EXECUTE IMMEDIATE 'DROP INDEX ' || aud_row.key_col_idx;
        exception
          when others then
            if sqlcode = -01418 then
              dbms_output.put_line(' index does not exist ');
            else
              dbms_output.put_line(sqlcode);
              raise;
            end if; 
        end;
      END LOOP;
    END;
    /

  • For Loop and Void Method Questions

    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)?
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now.
    for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Array
        public static void main(String[] args)
            int howNum = 0;
            int whichNum = 0;     
            double[] numArray;
            boolean invalidInput = true;
            String howManyNumbers, enterYourNumbers, wantToContinue;
      do // repeat program while "y"
          do // repeat if invalid input
            howManyNumbers = JOptionPane.showInputDialog
                        ("How many numbers do you want to enter");                     
            try
                 howNum = Integer.parseInt(howManyNumbers);
                 invalidInput =  false;
            catch (NumberFormatException e )
                howManyNumbers = JOptionPane.showInputDialog
                            ("How many numbers do you want to enter");
          while (invalidInput);
          for (int index = 0; index < howNum; index++) // process each number in the array
              enterYourNumbers = JOptionPane.showInputDialog   
                            ("Enter a number between 1 and 100");                       
              numArray = new double[howNum]; 
            try
                numArray[index] = Double.parseDouble(enterYourNumbers);
            catch (NumberFormatException e)
                    enterYourNumbers = JOptionPane.showInputDialog
                              ("Enter a number between 1 and 100");                          
                DecimalFormat fmt = new DecimalFormat ("###,###.00");
                JOptionPane.showMessageDialog(null, enterYourNumbers + " "  + "squared is "  + fmt.format(calcSquare(numArray[index]))
                                              + "\n" + enterYourNumbers + " " +  "cubed is " + fmt.format(calcCube(numArray[index])));                                                                           
                wantToContinue = JOptionPane.showInputDialog ("Do you want to continue(y/n)? ");
      while (wantToContinue.equalsIgnoreCase("y"));
        public static double calcSquare(double yourNumberSquared)
            return yourNumberSquared * yourNumberSquared;       
        public static double calcCube(double yourNumberCubed)
           return yourNumberCubed * yourNumberCubed * yourNumberCubed;              
        public static void calcAverage(double yourNumberAverage)
    }

    DeafBox wrote:
    Question 1: How would I write a for loop that repeats the according to the number entered, to prompt the user to enter a number (double) between 1 and 100. If the number is outside this range it is not accepted. Use a while loop instead.
    Question: 2 Also how would I write a for loop to do sum and find the average of the array numbers in a seperate void method( does not return anything to the main method)? Why would you want to use 2 methods. Use the loop to sum the numbers. Then after the loop a single line of code calculates the average.
    Question: 3 (first code snippet) With my for loop that is used to process each number in the array and square it and cube it and display the results to 2 decimal places. How do I make it so say I want the array to allow me to enter 2 numbers (so I enter 2 numbers) then it asks me to enter a number between 1 -100 (which will prompt 2 times) that it shows me the results for the entered numbers between 1-100 after one another instead of number then result number then result like I how it now. If I understand you correctly, use 2 loops. One gathers user inputs and stores them in an array/List. The second loop iterates over the array/List and does calculations.

  • How do I use an enhanced for loop / for each on my ViewObjectImpl ?

    Guys and Gals,
    With all of my newly acquired Java knowledge in tow, I spent this weekend cleaning up all of my code, dealing mainly with for loops. I converted them from a huge mess to a for each type loop using language such as ...
        RowSet priceUpdateRows = (RowSet)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        { // do operations on row... which makes perfect sense to me. For each Row in the RowSet, do something. It doesn't, however, makes sense to the compiler. It pouts and gives me a "foreach not applicable to expression type" error. So I read up on iterators and such, messed with code examples, and still can't get the RowSet to iterate with the above code. Could I make RowSet implement Iterable? How would I do that? I tried to create a class called RowSetExt which extended RowSet and implemented Iterable, but then I got a class cast exception.
    I know I could implement something like the following or a while(hasNext()) but they're really not what I'm looking for.
    ViewObject vo = … < Get ViewObject > …
    RowSetIterator rsi = vo.createRowSetIterator("rowsRSI");
    while (rsi.hasNext())
         Row row = rsi.next();
         row.setAttribute("YourAttribute",your_value);
         rsi.closeRowSetIterator();How do I make the for(Row row : <RowSet>) example work? Or could someone point me in a direction?
    Will

    One thing I tried was to make a framework extension class for my ViewObjectImpls
    public class PcsViewObjectImpl
      extends ViewObjectImpl
      implements Iterable<Row>
      Set<Row> set = new HashSet<Row>();
      public Iterator<Row> getRows()
        return set.iterator();
      public Iterator<Row> iterator()
        return getRows();
    }AppModuleImpl
        PriceUpdateRowsViewRowImpl priceUpdateRows = (PriceUpdateRowsViewRowImpl)((PriceUpdatesViewRowImpl) priceUpdate).getPriceUpdateRowsView();
        for (Row priceUpdateRow: priceUpdateRows)
        {However, this gives me a class cast exception at runtime. But I would think some kind of extension class would be the way to go ... ?

Maybe you are looking for

  • How can i detect if the picture or swf file is produced from legal flash?

    I have recently bought images and swf files from a student for my website. I've just realized that the images and swf might be from pirated flash product because i found out that the original flash is really and i mean really pricey! I don't believe

  • About Terms of Payment for PO

    Dears, I use a term of payment 0001 in a purchase order. the term of payment are: 5% in 14 days, 3% in the next 30 days. When I create a po , carry out GR, I process invoice verification. But in invoice verification for the PO, the system doesn't car

  • Why does the Q10 an OLED display...​.

    why does the Q10 an OLED display? there is not a long time after a problem with the color?

  • Typical Lead Scenario_URGENT!!!!

    Hi to all. I have a scenario wrt "Lead"      I am running a email Campaign which asks for Customers interest towards a Product.    Now who ever shows Clicks on Yes Button in the email , they need to be collected separately(for which there is a standa

  • BOFC MS SQL Server migration to Oracle

    Hello, We use BOFC, Intercompany with MS SQL Server 2008 R2 DB. Customer asks us about possibility migration MS SQL Server 2008 R2 to Oracle 11g. I didn't find any information in SMP,  lot of information about migration NW systems, but no information