For loop in jstl
Hi i'm wondering what is the format of a for loop in jstl.
for example:
my for loop:
for(int i = 0; i< stringArray.Length(); i++){
i++;
thanks
<c:forEach var="i" items="stringArray">
${i}
</c:forEach>Note: stringArray should be a variable in scope, and not a scriptlet variables.
ram.
Similar Messages
-
How convert java FOR loop into taglib directive
hi all,
I have following code in my Jsp. It is working but, we dont want to use java FOR loop anymore. Instead use corresponding taglib directive.
How can i convert this Java FOR loop into taglib implementation of FOR loop ?
<%
for(int i=0;i< arrMemberBenefit.length;i++) {
pageContext.setAttribute("arrMemberBenefiti", arrMemberBenefit);
System.out.println("PCPNAME: " + arrMemberBenefit[0].getPcpName());
%>
<tr class="rowOdd">
<td headers="t1h1" class="first"><c:out value="${arrMemberBenefiti.member.firstName}${space}${arrMemberBenefiti.member.lastName}" /></td>
<td headers="t1h2" class="last"><c:out value="${arrMemberBenefiti.pcpName}" /></td>
</tr>
<%}
%>
pl any help highly apprecialted
ppUsing the JSTL forEach tag:
I have used your variable name for arrMemberBenefiti
myself I would probably call it something like memberBenefit
You may need to put the array into an attribute to begin with
// just in case
<% pageContext.setAttribute("arrMemberBenefit", arrMemberBenefit); %>
// and the actual JSTL loop
<c:forEach var="arrMemberBenefiti" items="${arrMemberBenefit}">
<tr class="rowOdd">
<td headers="t1h1" class="first"><c:out value="${arrMemberBenefiti.member.firstName}${space}${arrMemberBenefiti.member. lastName}" /></td>
<td headers="t1h2" class="last"><c:out value="${arrMemberBenefiti.pcpName}" /></td>
</tr>
</c:forEach>Cheers,
evnafets -
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
AbyThis 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? -
Hi all,
I am trying to implement a custom "for loop tag". But it seems to me that there is a type conversion problem. I've tried many ways to fixed it but I still cannot get it to work. I've dug through my books, searched the internet and this forum but I can't found anythig useful. I am really lost now! Can anyone help me with this? Many many many thanks!!
loopTag.jsp
<%@ taglib prefix="myTag" uri="/WEB-INF/myTag.tld" %>
<% int num=5; %>
<myTag:loop index="i" count="<%=num%>">
body1here: i expr: <%=i%> i property: <jsp:getProperty name="i" property="value"/> <br>
</myTag:loop>
myTag.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>simple</shortname>
<tag>
<name>loop</name>
<tagclass>myTag.LoopTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>for loop</info>
<attribute>
<name>index</name>
<required>true</required>
</attribute>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
LoopTag.java
package myTag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;
public class LoopTag extends BodyTagSupport {
String index;
int count;
int i=0;
public void setIndex(String index){
this.index=index;
public void setCount(String count){
this.count=Integer.parseInt(count);
public int doStartTag() throws JspException {
return EVAL_BODY_TAG;
public void doInitBody() throws JspException {
pageContext.setAttribute(index, i);
i++;
public int doAfterBody() throws JspException {
try {
if (i >= count) {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
return SKIP_BODY;
else{
pageContext.setAttribute(index, i);
i++;
return EVAL_BODY_TAG;
catch (IOException ex) {
throw new JspTagException(ex.toString());
Error message:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: 4 in the jsp file: /loopTag.jsp
Generated servlet error:
The method setCount(String) in the type LoopTag is not applicable for the arguments (int)
An error occurred at line: 5 in the jsp file: /loopTag.jsp
Generated servlet error:
i cannot be resolved
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:409)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.11 logs.I took the custom for-loop one step further and now it can be nested with in other for-loop.
Hope this is the last time I have to reinvent the wheel. Now I REALLY apprecate JSTL!!
loopTag.jsp
<%@ taglib prefix="myTag" uri="/WEB-INF/myTag.tld" %>
<% int row = 5; %>
<% int col = 5; %>
<table border=0>
<myTag:loop index="i" count="<%= row %>">
<tr>
<myTag:loop index="j" count="<%= col %>">
<td>index: i=<myTag:printIndex parentLevel="2" /> j=<myTag:printIndex parentLevel="1" />, <br></td>
</myTag:loop>
</tr>
</myTag:loop>
</table>
myTag.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>simple</shortname>
<tag>
<name>loop</name>
<tagclass>myTag.LoopTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>for loop</info>
<attribute>
<name>index</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>printIndex</name>
<tagclass>myTag.LoopPrintTag</tagclass>
<bodycontent>JSP</bodycontent>
<info>for loop print</info>
<attribute>
<name>parentLevel</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
LoopTag.java
package myTag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.util.Hashtable;
import java.io.Writer;
import java.io.IOException;
public class LoopTag extends BodyTagSupport {
String index;
int count;
int i=0;
public void setIndex(String index){
this.index=index;
public String getIndex(){
return String.valueOf(pageContext.getAttribute(index));
public void setCount(int count){
this.count=count;
public int doStartTag() throws JspException {
i = 0;
return EVAL_BODY_TAG;
public void doInitBody() throws JspException {
pageContext.setAttribute(index, i);
i++;
public int doAfterBody() throws JspException {
try {
if (i >= count) {
bodyContent.writeOut(bodyContent.getEnclosingWriter());
return SKIP_BODY;
else{
pageContext.setAttribute(index, i);
i++;
return EVAL_BODY_TAG;
catch (IOException ex) {
throw new JspTagException(ex.toString());
LoopPrintTag.java
package myTag;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
public class LoopPrintTag extends BodyTagSupport {
private int parentLevel = 1;
public int doStartTag() throws JspTagException {
LoopTag parent = (LoopTag)findAncestorWithClass(this, LoopTag.class);
for(int i=1; i<parentLevel; i++){
parent = (LoopTag)findAncestorWithClass(parent, LoopTag.class);
if (parent == null) {
throw new JspTagException("print not inside loop");
else{
try {
JspWriter out = pageContext.getOut();
out.print(parent.getIndex());
} catch(IOException ioe) {
System.out.println("Error in printTag: " + ioe);
return(SKIP_BODY);
public void setParentLevel(int _parentLevel){
if(_parentLevel > 0){
parentLevel = _parentLevel;
Output:
index: i=0 j=0, index: i=0 j=1, index: i=0 j=2, index: i=0 j=3, index: i=0 j=4,
index: i=1 j=0, index: i=1 j=1, index: i=1 j=2, index: i=1 j=3, index: i=1 j=4,
index: i=2 j=0, index: i=2 j=1, index: i=2 j=2, index: i=2 j=3, index: i=2 j=4,
index: i=3 j=0, index: i=3 j=1, index: i=3 j=2, index: i=3 j=3, index: i=3 j=4,
index: i=4 j=0, index: i=4 j=1, index: i=4 j=2, index: i=4 j=3, index: i=4 j=4, -
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? ThanksThanks 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 KBHere'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 AMAdding 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 PMPROCEDURE "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,
NobleDECLARE
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.
Maybe you are looking for
-
Batch split not happening during delivery
Hi Experts, I have enough of stock for a material with different batches (with different expiry dates). When I create an order for qty 100, system confirms it on a certain date taking 1st batch nearest to expiry date, as per the search startegy set i
-
Creative 5.1 inspire 5300 Black slots not working
Hi I bought 5.1 creative inspire 5300 Please help me as only two speakers and woofer are working which are plugged in red slot of woofer. the remaining three speakers including center speaker are not working if i interchange them to red pluggs it is
-
Recreating folders in Itunes library
I installed Itunes version 8 this past summer and found that my entire music library had been converted to HTML. I did a search on the web and found out how to get rid of the HTML and get my folders back in my library (ironically it was on the Apple
-
Exporting photos as JPG at 300 pixels per inch has become very slow. I using Lightroom V1.1, Windows XP home SP2, P4 3GHz, 1GB ram, 300 GB SATA with 115 GB free. It has taken 1 hour to export 130 JPG files converted from a 6.1 mega pixel camera raw f
-
Truncate SQL 2008 R2 log files
How do I truncate a log file. Running out of space. Help is appreciated. Thanks Dave Kozlowski