For loop syntax

greetings people and evnafets
Can any one please help me with the below mentioned code
i'm a getting error string type cast.
At run time i'm entering the value for first name (param.firstname).According to the for loop sysntax this has to be an int however param .first name returns a string .Can any one of u tell me how to handle this scenario
<html>
<head>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<title>login.jsp</title>
</head>
<body>
<table>
<c:forEach var="counter" begin="1" end="${param.firstname}"/>
<input type="text" name= "<c:out value="input_${counter}" />"> <br>
</c:forEach>
</table>
</body>
</html>
regards
Aby

This version of the for loop takes numbers.
If param.firstname evaluates to "10" its fine.
Ie start at 1 and go to 10.
If param.firstname evaluates to "Peggie-Sue" its not.
Start at 1 and go to "Peggie-Sue" doesn't really make sense now does it?
Either use a different parameter, or only pass in a number.
What has the parameter firstname got to do with how many text fields you generate?

Similar Messages

  • Can I use a for loop to add anonymous ActionListener objects?

    I have a setListener() method that has the following inside:
    for(int k = 0; k < buttons.length; k++)
        buttons[k].addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                g2.setColor(colors[k]);
    }I have a JButton array and a Color array and I was hoping I could add them quickly in one shot rather than manually adding an anonymous ActionListener 9 times (I have 9 components). It tells me I need to make k final for an inner class and when I tested it by removing the for loop and keeping k as a final integer, it works. Is there a medium such that I can achieve what I want more or less while respecting Java's syntax?
    Any input would be greatly appreciated!
    Thanks in advance!

    s3a wrote:
    The local variable exists on the stack for as long as the method is executing. Once the method ends, that variable no longer exists. The newly created object, however, can continue to exist long after the method has ended. So when it's referring to variable X, it cannot refer to the same X as the one in the method, because that variable may no longer exist.Sorry for picking on little details but I am still not fully satisfied.
    Earlier I questioned if the local variable changed, but now let's say that that variable no longer exists at all, why does that even matter if the inner class copied the value and is keeping it for itself? What do you mean? The variable that existed in the method ceased to exist when the method ended. The inner class, however, can continue to live on, and can continue to refer to what we see as the same variable. However, it obviously can't be the same variable, since, in the world of the inner class, it still exists, while in the world of the method, it does not.
    This is completely independent of whether the variable changes or not. Regardless or whether the variable changes we still need two copies--one that goes away when the method's stack frame is popped, and one that lives on as long as the inner object does.
    Then, because there are two copies, the designers decided that the variable has to be final, so that they wouldn't have to mess with the complexity of keeping two variables in sync.
    That explanation leads me to believe that there is no copy and that there is some kind of "permanent umbilical cord" between the inner class and the local variable.Wrong. There has to be a copy. How else could the inner class keep referring to it after the method ends?
    Also, does marking it as final force it to be a permanent constant "variable" even if it's not a field "variable"? Or, similarly, does making a "variable" final make Java pretend that it is a field "variable"?Making a variable final does exactly one thing: It means the value can't change after it's been initialized. This is true of both fields and locals.
    As for the "pointless" byte-counting, I really don't see how it's confusing unless you're an absolute beginner. If I see somebody using a byte, I assume they have a real reason to do so, not pointless byte-hoarding. Then when I see that it's just a loop counter, I wonder WTF they were thinking, and have to spend some time determining if there's a valid reason, or if they're just writing bad code. Using a byte for a loop counter is bad code.
    I could then ask, why are people not using long instead of int and saying that that's using int is too meticulous?Part of it is probably historical. Part of it is because at 4 bytes, and int is exactly on word on the vast majority of hardware that Java has targeted since it came out. 8-byte words are becoming more common (64-bit hardware) but still in the minority.

  • PL/SQL block to create temporary table + load via cursor for loop

    Assume I have a table that contains a subset of data that I want to load into a temporary table within a cursor for-loop. Is it possible to have a single statement to create the table and load based on the results of the fetch?
    I was thinking something like:
    Declare CURSOR xyz is
    CREATE TABLE temp_table as
    select name, rank, serial number from
    HR table where rank = 'CAPTAIN'
    BEGIN
    OPEN xyz
    for name in xyz
    LOOP
    END LOOP
    What I see wrong with this is that the table would be created multiple times which is why this syntax is not acceptable. I'd prefer not to have to define the temporary table then load in two sepearte SQL statements and am hoping a single statement can be used.
    Thanks!

    What is the goal here?
    If you're just going to iterate over the rows that are returned in a cursor, a temporary table is unnecessary and only adds complexity. If you truly need a temporary table, you would declare it exactly once, at install time when you create all your other tables. You'd INSERT data into the temp table and the data would only be visible to the session that inserted it.
    Justin

  • For loop is not working

    Hi,
    I am using a if condition that will first check if the above command ran successfully if the errorlevel is 0 then execute the condition inside the if condition. My syntax is as follows
    if %errorlevel%==0 ( for /f "delims=" %%x in ('dir /b/od C:\Folder ') do set recent=%%x
    set FILE=%recent%
    echo %FILE%
    echo "hello world"
    ) else ( exit 1 
    the for loop is finding the latest file inside the C:\Folder .
    The for loop is working fine , if I remove the if condition, but failing when it is inside the if condition. 
    Kindly help.
    Thanks,
    Ashis

    ":eof" is an inbuilt label that is assumed to be at the end of the code. "Goto :eof" causes the program to jump to that label. Now consider this construct. It demonstrates that "goto :eof" terminates the current segment but not necessarily the batch file.
    @echo off
    call :Sub1
    call :Sub2
    goto :eof
    :Sub1
    if  %value% GTR 5 goto :eof
    echo The value is %value%
    goto :eof
    :Sub2
    echo The date is %date%
    if /i %UserName% EQU Ashissau goto :eof
    echo You are not authorised to use this PC.
    goto :eof

  • How to return multiple tags (based on different checks) in a for loop?

    Hi,
    I'm trying to return multiple elements, based on different checks that are done in the XQuery, within a for loop. But I'm getting syntax errors at any attempt to do this.
    This is the structure of what I'm trying to do:
              <ActionList>
         <ACtion>
    let $total := count(...)
    for $x in (1 to $total)
         let $lineItems := $someVariable/*:Items/*:Item[$x]
         return
              if(...)
                        <Qty1>{...}</Qty1>
                             else     ""
                        if(...)
                        <Qty2>{...}</Qty2>
                             else ""
                   {                                       if(...)
              <Qty3>{...}</Qty3>
                             else ""
              <LinesList>
                             let $totalcount(...)
                             for $y in (1 to $totalcount(...)
                                  let $DTL := $someVariable*:DTL[$y]
                             return
                             <Line>
                                  <Carrier>{...}</Carrier>
                                  <Path>{...}</Path>
                                  <CA>{
                                       if(...)
                                            data($$someVariable/*:CA)
                                       else
                                  }</CA>
                                  <RE>{
                                       if(...)
                                            data($someVariable*:CA[@XX="RG"])
                                       else
                                  }</RE>
                                  <Time>{
                                       if(...)
                                            data($someVariable*:CA[@XX="BN"])
                                       else
                                                                     </Time>
                                  </Line>
                        </LinesList>
                                                 </ACtion>
                                                 </ActionList>
    I'm not able to return elements without having their father being returned as well, I just want to iterate over those fields and, based on that verification, decide whether they should be returned or not.
    Can someone please advise?

    An example anyway...
    Input document ($d) :
    <ns0:Items xmlns:ns0="http://my.company.org/my-namespace">
      <ns0:Item type="A">
        <ns0:Qty>2</ns0:Qty>
        <ns0:UnitPrice>10.00</ns0:UnitPrice>
        <ns0:DTL>
          <ns0:Article>ART001</ns0:Article>
          <ns0:DispatchDate>2012-01-20</ns0:DispatchDate>
          <ns0:Destination direct="1">Location1</ns0:Destination>
        </ns0:DTL>
        <ns0:DTL>
          <ns0:Article>ART002</ns0:Article>
          <ns0:DispatchDate>2012-01-21</ns0:DispatchDate>
          <ns0:Destination direct="1">Location2</ns0:Destination>
        </ns0:DTL>
      </ns0:Item>
      <ns0:Item type="B">
        <ns0:Mass>5</ns0:Mass>
        <ns0:Unit>kg</ns0:Unit>
        <ns0:DTL>
          <ns0:Article>ART003</ns0:Article>
          <ns0:DispatchDate>2012-01-20</ns0:DispatchDate>
          <ns0:Destination direct="1">Location3</ns0:Destination>
        </ns0:DTL>
        <ns0:DTL>
          <ns0:Article>ART004</ns0:Article>
          <ns0:DispatchDate>2012-01-21</ns0:DispatchDate>
          <ns0:Destination direct="1">Location4</ns0:Destination>
        </ns0:DTL>
        <ns0:DTL>
          <ns0:Article>ART005</ns0:Article>
          <ns0:DispatchDate>2012-01-22</ns0:DispatchDate>
          <ns0:Destination direct="2">Location5</ns0:Destination>
        </ns0:DTL>
      </ns0:Item>
    </ns0:Items>XQuery :
    declare namespace ns0 = "http://my.company.org/my-namespace";
    <DispatchInfo>
      for $i in $d/ns0:Items/ns0:Item
      return
      <Parcel>
        if ($i/@type = "A")
          then <Amount>{xs:decimal($i/ns0:Qty * $i/ns0:UnitPrice)}</Amount>
          else <Weight>{concat($i/ns0:Mass, " ", $i/ns0:Unit)}</Weight>
      , for $j in $i/ns0:DTL
        return
        <Article>
          <Num>{data($j/ns0:Article)}</Num>
        , <Dt>{data($j/ns0:DispatchDate)}</Dt>
        , if ($j/ns0:Destination/@direct = "1")
            then <Dest>{data($j/ns0:Destination)}</Dest>
            else ()
        </Article>                 
      </Parcel>
    </DispatchInfo>Output :
    <DispatchInfo>
      <Parcel>
        <Amount>20</Amount>
        <Article>
          <Num>ART001</Num>
          <Dt>2012-01-20</Dt>
          <Dest>Location1</Dest>
        </Article>
        <Article>
          <Num>ART002</Num>
          <Dt>2012-01-21</Dt>
          <Dest>Location2</Dest>
        </Article>
      </Parcel>
      <Parcel>
        <Weight>5 kg</Weight>
        <Article>
          <Num>ART003</Num>
          <Dt>2012-01-20</Dt>
          <Dest>Location3</Dest>
        </Article>
        <Article>
          <Num>ART004</Num>
          <Dt>2012-01-21</Dt>
          <Dest>Location4</Dest>
        </Article>
        <Article>
          <Num>ART005</Num>
          <Dt>2012-01-22</Dt>
        </Article>
      </Parcel>
    </DispatchInfo>

  • Is this another form of a cursor for loop?

    Hi,
    I'm working, in Oracle 10gR2 in Windows XP, on a stored procedure that was given to me mostly completed and I'm trying to decypher the syntax of the cursor.
    CREATE OR REPLACE PROCEDURE p_proc1(p_from_date IN DATE
                                                        ,p_to_date   IN DATE
                                                        ,p_result_cur   IN OUT dbo.pkg_q.ref_cursor) IS
    BEGIN
        OPEN ,p_result_cur FOR WITH wr AS(
            SELECT wr.F1
                  ,wr.F2
                  ,wr.F3
                  ,wr.F4
              FROM work_report wr
             WHERE 1 = etc.               )
                SELECT AF1
                           ,AF2
                           ,AF3
                FROM history h
                WHERE something = somethingelse;Is the 'OPEN ,p_result_cur FOR WITH wr AS(' code just a complex cursor for loop? and how does the 'WITH' fit into it?
    Thank you!

    Hi,
    Paul Davis wrote:
    Hi,
    I'm working, in Oracle 10gR2 in Windows XP, on a stored procedure that was given to me mostly completed and I'm trying to decypher the syntax of the cursor.
    CREATE OR REPLACE PROCEDURE p_proc1(p_from_date IN DATE
    ,p_to_date   IN DATE
    ,p_result_cur   IN OUT dbo.pkg_q.ref_cursor) IS
    BEGIN
    OPEN ,p_result_cur FOR WITH wr AS(
    SELECT wr.F1
    ,wr.F2
    ,wr.F3
    ,wr.F4
    FROM work_report wr
    WHERE 1 = etc.               )
    SELECT AF1
    ,AF2
    ,AF3
    FROM history h
    WHERE something = somethingelse;Is the 'OPEN ,p_result_cur FOR WITH wr AS(' code just a complex cursor for loop? and how does the 'WITH' fit into it?I think the comma before p_ref_result_cur is a typo; there should only be space there:
    OPEN p_result_cur FOR WITH wr AS ...There's no loop in the fragment you posted: the OPEN statement does just that; it opens the cursor so later FETCH statements (perhaps inside a loop) can get data.
    "WITH sub_query AS ( .... ) SELECT ..." is one way of writing a query.
    For details, see the SQL Language manual:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9758

  • Teststand XML Translator For LOOP Step

    HI, I'm trying to write an XML translator usinc the C++ example. So far I made work "if" , "while" , "end" and i'm trying to make the "for" loop working as well but i have a issue when i insert the dataProperty.
    The XML code i wrote id the following :
    <Data dataProperty="InitializationExpr" type = "string"> <Value>"Locals = 0"</Value> </Data><Data dataProperty="ConditionExpr" type = "string"> <Value>"Locals &lt; 10"</Value> </Data><Data dataProperty="IncrementExpr" type = "string"> <Value>"Locals += 1"</Value> </Data> 
    so the issie is that is i use the " " it works in the PropertyBrowser window but not in the For Loop window and if i dont use the " " is the opposite.
    I even tried to change the property CustomLoop followinf the same syntax but it doesnt work:
    <Data dataProperty="CustomLoop" type = "bool"> <Value>true</Value> </Data> 
    can anybosy help me with this?
    thank you
    Luca

    If I use Locals.X == 10 it gives me an error in the Number of Loop field in the For Loop window. What i really would like to know is how to set the properties for every step because beside few of them that i can set with dataProperty="ConditionExpr" or dataProperty="TitleExpr" i dont know how to set the other ones.
    For istance if i want to have a Sequence Call (I already wrote code so to have more then one Sequence) in a Sequence that calls another one i can have code like this:
    <Sequence name="MainSequence">
    <Step name="CallSeq2" type="SeqCall">
    </Step>
    </Sequence>
    <Sequence name="MainSequence2">
    </Sequence>
    now I dont know how to pass values to the step so to fill the File Pathname and Sequence fields in the Module window can I use dataProperty? and in cas I can what is the Sintax?
    thank you
    Luca

  • Removing Items While Using New For Loop

    Consider this:
    ArrayList<String> a = new ArrayList<String>();
    ... add some stuff ...
    for(String s : a) {
    // Do some stuff
    if(some_condition) {
    a.remove(s);
    This will cause a ConcurentModificationException the a.remove(s) is ever run. Is there anyway to call the iterator.remove() method instead? The new syntax is much cleaner, and I'd like to use it, but I need to be able to call iterator.remove()
    Anyone?

    I think the code should iterate through a, putting
    references to objects in an auxillary array and then
    the loop will go through the auxilary array rather
    than the original data structure. This perfectly
    reasonable, but different implementation results in
    drastically different results (the example above would
    work fine). I see this as an issue of these general
    language features being defined to close to the metal.
    Their semantics are defined by their implementation
    not by a sound language design decision that is
    agnostic to different implementations.The enhanced for loop is defined in terms of java.lang.Iterable, a very simple interface, which can be implemented in many different ways. You can't get much farther from the metal. The concurrent modification exception is a feature of particular implementations of that interface. If you don't like those implementations, use others that behave differently. For example, you could use one of the CopyOnWrite collections implementations in java.util.concurrent, which never throw a concurrent modification exception. Your suggestion to copy the elements into an array is one (inefficient) implementation mechanism for such collections.

  • 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

Maybe you are looking for

  • Ipod mini versus windows vista

    i just got a used ipod mini (4g version). i used the installer disc that came with it, udated itunes to 9.1, plugged my ipod in and nothing. the ipod comes up charging and on the main menu, but other than that, goose egg. is vista or windows media pl

  • Disk greater 8GB with old BIOS

    I try to get a 40GB Western Digital WD Caviar 450AA work properly on the secondary IDE controller as a master drive. It should have the function as a data storage. I got the patch 110202-01 applied on my system, which should get disks greater than 8G

  • Functional Area Determination for Balance Sheet Accounts

    Hi all, We are on 4.7C and want to activate Functional Area updation on Vendor Invoices but when we go to FB60 and create manual Vendor Invoice the Field FKBER does not appear. We have made the FSG optional on the reconciliation account already. We h

  • How do i get my pictures back that were backed up with icloud?

    I updated to iOS 7 and the degraded back but my icloud backed up when I was in iOS 7 and now i am back to iOS 6.1.4 and it says i can not restore from my backup but all I really want from my backup is the pictures. so how do i do that?

  • Wifi-select on Install media?

    Why not put wifi-select package on the install media for easy wifi setup?