Double for loop

Hi,
I am trying to modify the content of a 2D for loop using a double for loop. But the result I am getting is always 0 in the loop i am getting... I am not really too sure of the problem. Can anyone help?
Thanks
Attachments:
example2.vi ‏32 KB

The results are not 0. the VI has replaced all of the elements in the intial array with random numbers. You've got an initial array with 3 rows and 3 columns but your inner for loop iterates 10 times. You cannot do a replace array element on an array element that is empty. You simply have to set the iteration count of the inner most for loop to be the same as the number of columns. You did that with the outermost for loop. Why did you use a constant of 10 for the inner loop?

Similar Messages

  • I'm doing a scan around a line by sampling data 360 degrees for every value of z(z is the position on the line). So, that mean I have a double for-loop where I collect the data. The problem comes when I try to plot the data. How should I do?

    I'm doing a scan around a line by sampling data 360 degrees for every value of z(z is the position on the line). So, that mean I have a double for-loop where I collect the data. The problem comes when I try to plot the data. How should I do?

    Jonas,
    I think what you want is a 3D plot of a cylinder. I have attached an example using a parametric 3D plot.
    You will probably want to duplicate the points for the first theta value to close the cylinder. I'm not sure what properties of the graph can be manipulated to make it easier to see.
    Bruce
    Bruce Ammons
    Ammons Engineering
    Attachments:
    Cylinder_Plot_3D.vi ‏76 KB

  • Create multiple VIs using a for loop

    Hi,
    I'm still pretty new to LabVIEW, so this question might be easy for you guys here..
    I'll simplify what I'm trying to do.
    I've got two numeric controllers that act as the rows and columns of a matrix.
    I'd like to take those numbers from these two controllers and use them to create a matrix of a certain picture.
    Example:
    The rows controller is given 3, and the columns controller is given 4.
    Using these numbers I would like the end result to show a certain image (let's say, a cube) multiplied on a 3 by 4 matrix.
    Let's say the picture is an X, then the end result should be:
    XXXX
    XXXX
    XXXX 
    I think I should be using a double for loop (one inside the other obviously), and I should also create the "position" property in order to display each picture of the cube in it's right place.
    The problem is that I don't know how to CREATE the pictures over and over again, while being able to control each one's position property.
    Any help would be GREATLY appreciated!
    Solved!
    Go to Solution.

    1) By "multiple VIs" I meant that I think that I need to create express VIs on the fly while running the for loop. I might be totally wrong here.
    2) Yes, by "numeric controllers" I meant numeric controls in the front panel.
    3) The matrix I'm referring too isn't an object nor a VI in LabVIEW but a virtual matrix that is the end result. I used the term "matrix" because the end result is actually a matrix (of rows and columns) of pictures..
    I'll try to elaborate and even simplify it more:
    Let's say I want to display one picture. That's easy, no problem there.
    Now let's say that I'd like to display n pictures on a one dimensional array. Just one row.
    What I think I need to do is to read from the numeric control in the front panel the number (n) of pictures, and then create them in a for loop, while using the "position" property to set the distance between each picture (using coordinates).
    My original question was just like the above, but for a two dimensional matrix/array. So I guess we can even simplify it even more, by saying it's only one dimensional.
    My way of action here might be totally wrong, and there might be an easier way or another way to go about this...
    Thanks for the quick answer!!  

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

  • A tunneled Excel refnum goes from a valid value to a NULL between iterations of a For Loop?

    How would a tunneled Excel refnum go from a valid value to a NULL between iterations of a For Loop?
    For
    some reason this works find in one VI and when executed and not in
    another.  Here's screen shots of the highlighted execution with probes
    appropriately. The "Open" refnum is passed into "Performance Test -
    Write Data To Files.vi".  That's where the trouble is.  You can see
    that it goes into the For Loop.  The first iteration is okay, but the
    second and subsequent iterations have the refnum NULL.  See images
    below.
    (I don't know how to delete an accidental double post, sorry)
    Message Edited by James DiLiberto on 01-22-2008 01:48 PM
    Attachments:
    Second Iteration1.jpg ‏158 KB
    First Iteration1.jpg ‏145 KB
    Second Iteration Error Dialog1.jpg ‏20 KB

    Is there any chance that the Insert Data Into Excel VI is closing the reference or that it is closed anywhere else (e.g. through a local or by having its owner destroyed)?
    I wouldn't expect the numeric value of the reference to change to 0, but since ActiveX is an external resource, I suppose that it's possible that the probe shows the number only if the resource is actually accessible.
    Try to take over the world!

  • For Loop in Struts ?(without Collections)

    Hi all,
    Pls tell me how can v use FOR LOOP IN JSP STRUTS without using scriplets and collections .
    suppose i want to display 20 times "hello world "in jsp .How can i display it using STRUTS as conventionally scriplets are not allowed in it.
    and Iterator is only for Collections .
    thanx

    TestBean.java
    * $Id: TestBean.java 54929 2004-10-16 16:38:42Z germuska $
    * Copyright 1999-2004 The Apache Software Foundation.
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    * http://www.apache.org/licenses/LICENSE-2.0
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
    package org.apache.struts.webapp.exercise;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Vector;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.util.LabelValueBean;
    * General purpose test bean for Struts custom tag tests.
    * @version $Rev: 54929 $ $Date: 2004-10-16 17:38:42 +0100 (Sat, 16 Oct 2004) $
    public class TestBean extends ActionForm {
    // ------------------------------------------------------------- Properties
    * A collection property where the elements of the collection are
    * of type <code>LabelValueBean</code>.
    private Collection beanCollection = null;
    public Collection getBeanCollection() {
    if (beanCollection == null) {
    Vector entries = new Vector(10);
    entries.add(new LabelValueBean("Label 0", "Value 0"));
    entries.add(new LabelValueBean("Label 1", "Value 1"));
    entries.add(new LabelValueBean("Label 2", "Value 2"));
    entries.add(new LabelValueBean("Label 3", "Value 3"));
    entries.add(new LabelValueBean("Label 4", "Value 4"));
    entries.add(new LabelValueBean("Label 5", "Value 5"));
    entries.add(new LabelValueBean("Label 6", "Value 6"));
    entries.add(new LabelValueBean("Label 7", "Value 7"));
    entries.add(new LabelValueBean("Label 8", "Value 8"));
    entries.add(new LabelValueBean("Label 9", "Value 9"));
    beanCollection = entries;
    return (beanCollection);
    public void setBeanCollection(Collection beanCollection) {
    this.beanCollection = beanCollection;
    * A multiple-String SELECT element using a bean collection.
    private String[] beanCollectionSelect = { "Value 1", "Value 3",
    "Value 5" };
    public String[] getBeanCollectionSelect() {
    return (this.beanCollectionSelect);
    public void setBeanCollectionSelect(String beanCollectionSelect[]) {
    this.beanCollectionSelect = beanCollectionSelect;
    * A boolean property whose initial value is true.
    private boolean booleanProperty = true;
    public boolean getBooleanProperty() {
    return (booleanProperty);
    public void setBooleanProperty(boolean booleanProperty) {
    this.booleanProperty = booleanProperty;
    * A multiple-String SELECT element using a collection.
    private String[] collectionSelect = { "Value 2", "Value 4",
    "Value 6" };
    public String[] getCollectionSelect() {
    return (this.collectionSelect);
    public void setCollectionSelect(String collectionSelect[]) {
    this.collectionSelect = collectionSelect;
    * A double property.
    private double doubleProperty = 321.0;
    public double getDoubleProperty() {
    return (this.doubleProperty);
    public void setDoubleProperty(double doubleProperty) {
    this.doubleProperty = doubleProperty;
    * A boolean property whose initial value is false
    private boolean falseProperty = false;
    public boolean getFalseProperty() {
    return (falseProperty);
    public void setFalseProperty(boolean falseProperty) {
    this.falseProperty = falseProperty;
    * A float property.
    private float floatProperty = (float) 123.0;
    public float getFloatProperty() {
    return (this.floatProperty);
    public void setFloatProperty(float floatProperty) {
    this.floatProperty = floatProperty;
    * Integer arrays that are accessed as an array as well as indexed.
    private int intArray[] = { 0, 10, 20, 30, 40 };
    public int[] getIntArray() {
    return (this.intArray);
    public void setIntArray(int intArray[]) {
    this.intArray = intArray;
    private int intIndexed[] = { 0, 10, 20, 30, 40 };
    public int getIntIndexed(int index) {
    return (intIndexed[index]);
    public void setIntIndexed(int index, int value) {
    intIndexed[index] = value;
    private int intMultibox[] = new int[0];
    public int[] getIntMultibox() {
    return (this.intMultibox);
    public void setIntMultibox(int intMultibox[]) {
    this.intMultibox = intMultibox;
    * An integer property.
    private int intProperty = 123;
    public int getIntProperty() {
    return (this.intProperty);
    public void setIntProperty(int intProperty) {
    this.intProperty = intProperty;
    * A long property.
    private long longProperty = 321;
    public long getLongProperty() {
    return (this.longProperty);
    public void setLongProperty(long longProperty) {
    this.longProperty = longProperty;
    * A multiple-String SELECT element.
    private String[] multipleSelect = { "Multiple 3", "Multiple 5",
    "Multiple 7" };
    public String[] getMultipleSelect() {
    return (this.multipleSelect);
    public void setMultipleSelect(String multipleSelect[]) {
    this.multipleSelect = multipleSelect;
    * A nested reference to another test bean (populated as needed).
    private TestBean nested = null;
    public TestBean getNested() {
    if (nested == null)
    nested = new TestBean();
    return (nested);
    * A String property with an initial value of null.
    private String nullProperty = null;
    public String getNullProperty() {
    return (this.nullProperty);
    public void setNullProperty(String nullProperty) {
    this.nullProperty = nullProperty;
    * A short property.
    private short shortProperty = (short) 987;
    public short getShortProperty() {
    return (this.shortProperty);
    public void setShortProperty(short shortProperty) {
    this.shortProperty = shortProperty;
    * A single-String value for a SELECT element.
    private String singleSelect = "Single 5";
    public String getSingleSelect() {
    return (this.singleSelect);
    public void setSingleSelect(String singleSelect) {
    this.singleSelect = singleSelect;
    * String arrays that are accessed as an array as well as indexed.
    private String stringArray[] =
    { "String 0", "String 1", "String 2", "String 3", "String 4" };
    public String[] getStringArray() {
    return (this.stringArray);
    public void setStringArray(String stringArray[]) {
    this.stringArray = stringArray;
    private String stringIndexed[] =
    { "String 0", "String 1", "String 2", "String 3", "String 4" };
    public String getStringIndexed(int index) {
    return (stringIndexed[index]);
    public void setStringIndexed(int index, String value) {
    stringIndexed[index] = value;
    private String stringMultibox[] = new String[0];
    public String[] getStringMultibox() {
    return (this.stringMultibox);
    public void setStringMultibox(String stringMultibox[]) {
    this.stringMultibox = stringMultibox;
    * A String property.
    private String stringProperty = "This is a string";
    public String getStringProperty() {
    return (this.stringProperty);
    public void setStringProperty(String stringProperty) {
    this.stringProperty = stringProperty;
    * An empty String property.
    private String emptyStringProperty = "";
    public String getEmptyStringProperty() {
    return (this.emptyStringProperty);
    public void setEmptyStringProperty(String emptyStringProperty) {
    this.emptyStringProperty = emptyStringProperty;
    * A single-String value for a SELECT element based on resource strings.
    private String resourcesSelect = "Resources 2";
    public String getResourcesSelect() {
    return (this.resourcesSelect);
    public void setResourcesSelect(String resourcesSelect) {
    this.resourcesSelect = resourcesSelect;
    * A property that allows a null value but is still used in a SELECT.
    private String withNulls = null;
    public String getWithNulls() {
    return (this.withNulls);
    public void setWithNulls(String withNulls) {
    this.withNulls = withNulls;
    * A List property.
    private List listProperty = null;
    public List getListProperty() {
    if (listProperty == null) {
    listProperty = new ArrayList();
    listProperty.add("dummy");
    return listProperty;
    public void setListProperty(List listProperty) {
    this.listProperty = listProperty;
    * An empty List property.
    private List emptyListProperty = null;
    public List getEmptyListProperty() {
    if (emptyListProperty == null) {
    emptyListProperty = new ArrayList();
    return emptyListProperty;
    public void setEmptyListProperty(List emptyListProperty) {
    this.emptyListProperty = emptyListProperty;
    * A Map property.
    private Map mapProperty = null;
    public Map getMapProperty() {
    if (mapProperty == null) {
    mapProperty = new HashMap();
    mapProperty.put("dummy", "dummy");
    return mapProperty;
    public void setMapProperty(Map mapProperty) {
    this.mapProperty = mapProperty;
    * An empty Map property.
    private Map emptyMapProperty = null;
    public Map getEmptyMapProperty() {
    if (emptyMapProperty == null) {
    emptyMapProperty = new HashMap();
    return emptyMapProperty;
    public void setEmptyMapProperty(Map emptyMapProperty) {
    this.emptyMapProperty = emptyMapProperty;
    // --------------------------------------------------------- Public Methods
    * Reset the properties that will be received as input.
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    booleanProperty = false;
    collectionSelect = new String[0];
    intMultibox = new int[0];
    multipleSelect = new String[0];
    stringMultibox = new String[0];
    if (nested != null)
    nested.reset(mapping, request);
    }

  • For loop question

    Hi here is a segment of my code:
    public void vietaLoop(){
         int loopParameter;
         final int START_CONDITION=0;
         final long END_CONDITION=no_Terms;
         double initialTerm = Math.sqrt(2)/2;
         double newTerm;
         double previousTerm;
         /* calculate the next PI term */
         newTerm = Math.sqrt(2+previousTerm);
         /* assign new term to previous */
         previousTerm = newTerm;
         for (loopParameter = START_CONDITION; loopParameter < END_CONDITION;
         loopParameter++)
         /* Prints the new PI approximation */
         System.out.println(+ newTerm);
    im having loads of trouble, above is how far I have got but I'm unable to 'call' the previous calculation to be included in the next calculation to calculate the new term of PI. as a result all my output is the same..... ie = 1.645.......
    If anyone could point me in the right direct... its really getting to me. Thanks.

    Hi there,
    Is this what you want?
    import java.awt.*;
    class vietaLoop
        public static void main(String[] args)
              int loopParameter;
              int no_Terms=10;
              int START_CONDITION=0;
              int END_CONDITION=no_Terms;
              double initialTerm=Math.sqrt(2)/2;
              double newTerm;
              double previousTerm;
              previousTerm=initialTerm;
              for (loopParameter=0; loopParameter<END_CONDITION;loopParameter++)
                   newTerm = Math.sqrt(2+previousTerm);
                   previousTerm = newTerm;
                   System.out.println(newTerm);
    }If you use it as a function, set it as
    public double vietaLoop(int noTerm)
    Then you can change no of term for looping.
    Regards
    John

  • Strange System.out.print behavior inside a for loop

    I'm trying to create a simple ASCII progress bar in the console that would display like this:
    |--------------------------------------------|
    ============================More equal signs would appear as time goes on. At least this is what I want to happen.
    Instead, what happens is, none of the equal signs are printed until the very end, after the for loop in which the System.out.print("=") statement is in, has exited.
    This is my code (probably more than necessary is shown, but the important part is the for loop):
        public void addSomeDiffys(int numOfDiffys, int minInt, int maxInt) {
            Diffy currentDiffy;
            System.out.println("\nCreating Diffys.");
            System.out.println("|--------------------------------------------|");
            for (int i=0; i < numOfDiffys; i++) {
                currentDiffy = new Diffy(minInt, maxInt);
                if ((i/(double)numOfDiffys)*100 % 2 == 0)
                    System.out.print("=");
                diffyList.add(currentDiffy);           
            System.out.println("\n" + diffyList.size() + " Diffys created.\n");
            System.out.println("Sorting according to highest rating...");
            Collections.sort(diffyList,Diffy.HIGHEST_RATING_ORDER);
            System.out.println("Done.\n");
        }I also tried changing the System.out.print("="); to System.out.println("="); This time it works as expected, its just not very pretty...
    I get something like this:
    |--------------------------------------------|
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =
    =So again, when I use println, rather than print, the equal signs are printed over time, slowly, as the progress increases. When using print, Nothing happens for a long time, and then suddenly they all appear after the for loop has terminated, which makes no sense.
    Thanks for any help.

    When using print, Nothing happens
    for a long time, and then suddenly they all appear
    after the for loop has terminated, which makes no
    sense.
    Yes it does make sense! The characters are buffered inside the PrintStream and written when there is a full line to write. You could try a flush() after each = is written but I have no confidence that it will make any difference.

  • Aborting from double while loops

    Hi,
    I am trying to do a X-Y movement with one of my piezostage automatically. It would be required for it to move in x-y direction for a certain user defined steps.
    However, I have problem with trying to abort the motion at will. Previously I have used a for loop and I know that there did not exist any stop condition for it and I have switched to a while loop. THe existing program structure has a double while loop with one while loop nested within another one.
    HOwever, I have a problem with terminating the program. The program will still finish the execution of the outer while loop before it goes out of the main while loop. I have used the same local variable which connects to the stop condition of both inner and outer while loop? Is there any methods to prevent any execution of the outer while loop and immediately looped out of the program?
    Thanks for your help!

    Yes, for the outer loop to regain control, the inner loop must finish first. It's all in the dataflow!
    (Of course the wait in the outer loop is not really necessary here because the outer loop speed is entirely governed by the inner loop, which must run at least once per iteration of the outer loop.)
    Don't confuse it with a situation where you have two parallel independent loops without any data dependency between them.
    Message Edited by altenbach on 01-06-2007 10:11 AM
    LabVIEW Champion . Do more with less code and in less time .

  • Why Isn't the for loop executing?

    here's the code,the for loop isn't executing,can anyone trouble shoot?
    import acm.program.ConsoleProgram;
    public class AddIntegerList extends ConsoleProgram {
    public void run(){
         for(int c=0;c<5;c++);{
         println("This is a programe to divide 2 numbers");
    double i = readDouble("enter num1: ");     
    double x = readDouble("enter num2: ");
    double ans = i/x;
    println("The answer to your division Is "+ans+ "");
              } by the way,this Is the first piece of java code that I have written. :D
    Edited by: Parastar on Oct 21, 2009 4:20 AM

    I dont think there should be a semicolon at the end of this
    for(int c=0;c<5;c++); Remove it and try running the program.
    Edited by: A.J.Bharanidharan on Oct 21, 2009 4:53 PM

  • How to maintain counter in a for loop

    Hi, 
      How do we track counter in a loop?Isn't it the way I implemented.? Please suggest.
    Regards.
    Solved!
    Go to Solution.
    Attachments:
    for loop counter.jpg ‏219 KB

    Both loops have errors, if you try to do for(i=60;i<120;i++) you're only running 60 loops, not 120.
    You should also disable the autoindexing on incoming arrays as you want some split array indexes (actually you can optimize it by extracting the constant a[30] before the 1st loop and the opposite on the 2nd. Now you're extracting 2 numbers from a 1D array instead of 1 from a 2D array ...
    The number on the select/sum function should be integers, no need to calculate doubles.
    The small array to sum it up is only max 170 numbers, it's ok although a sum in a shift register would be better.
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • Event handling for loop??

    Hi all,
    Been busy making this budget applet and have run into some trouble with my JTable. Each time a user inputs a selection, it is supposed to return values in the first column only. The next time a user inputs an amount, it should go into the next column, etc. As of now, the user inputs an amount and returns the values in all the columns.....How do i get the column # to increase each time a user inputs an amount? thanks!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.util.Arrays;
    import java.util.EventListener;
    import javax.swing.table.*;
    import javax.swing.border.Border;
    import javax.swing.border.LineBorder;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JScrollPane;
    //WRITE FOR LOOP..COLUMNS ++1 EACH TIME AN INPUT IS ENTERED..LAST COLUMN==TOTALS
    public class ProjectOne extends JApplet implements ActionListener , ItemListener, EventListener {
         private static String Enter = "Enter";
         private JPasswordField pass;
         JLabel money, inlabel, outlabel,result, taxwitheld, taxlabelsouth, quote, information;
         JButton input, cleartable, clear;
         Image img, butimg;
         JPanel top, left, bottom, middletop, east;
         ImageIcon arg;
         JRadioButton jrbyes, jrbno;
         ButtonGroup radgroup;
         JTextField moneyinput;
         String[] tableheadings = {"CATAGORIES","1", "2", "3","4","5", "TOTALS"};
         Object data[] [] = { { "Rent","","","","","",""},
                             {"Utilities","","","","","",""},
                             {"Groceries","","","","","",""},
                             {"Clothes","","","","","",""},
                             {"Bills","","","","","",""},
                             {"Automobile","","","","","",""},
         JScrollPane sp;
         JTable table;
         public void init()
              setLayout(new BorderLayout());
              setSize(850, 325);
              doNside();
              doEside();
              doWside();
              doSside();
              doCenter();     
         public void doNside()
              img = getImage( getCodeBase( ), "money-symbol.jpg" );
              arg = new ImageIcon(img);
              money = new JLabel("<HTML><FONT COLOR=GREEN>Alan Reno's Budget Applet               </FONT>", arg ,JLabel.RIGHT );
              money.setHorizontalTextPosition(JLabel.LEFT);
              top = new JPanel( new FlowLayout( ) );
              top.setBorder(BorderFactory.createLineBorder(Color.black));
              top.setBackground(Color.WHITE);
              top.add( money );
              add( top, BorderLayout.NORTH );
         public void doSside()
              bottom = new JPanel (new FlowLayout());
              taxwitheld = new JLabel("Display Taxes Witheld?", JLabel.CENTER);
              jrbyes = new JRadioButton ("yes");
              jrbno = new JRadioButton ("no");
              jrbyes.setOpaque(false);
              jrbno.setOpaque(false);
              jrbyes.addItemListener(this);
              jrbno.addItemListener(this);
              radgroup = new ButtonGroup();
              radgroup.add(jrbyes);
              radgroup.add(jrbno);
              Font font = new Font("Serif", Font.ITALIC,12);
              Border border = LineBorder.createGrayLineBorder();
              taxlabelsouth = new JLabel(" tax amount ");
              taxlabelsouth.setFont(font);
              taxlabelsouth.setBorder(border);
              bottom.setBackground(Color.WHITE);
             bottom.add(taxwitheld);
             bottom.add(jrbyes);
             bottom.add(jrbno);
             bottom.add(taxlabelsouth);
             add(bottom, BorderLayout.SOUTH);
         public void doEside()
              east = new JPanel (new GridLayout(2,1));
              quote = new JLabel ("<HTML><FONT SIZE=+1><CENTER><B>\"Healthy</B>"
                     +"<BR>Wealthy</BR>"
                     +"<BR>and</BR>"
                     +"<BR>Wise\"</BR></CENTER></FONT>", JLabel.CENTER);
              east.setBackground(Color.WHITE);
              table = new JTable(data, tableheadings);
              DefaultTableModel dmodel = new DefaultTableModel(data, tableheadings)
                   public boolean isCellEditable(int row,int column)
                        return false;
              table = new JTable(dmodel);
              table.setPreferredScrollableViewportSize(new Dimension( 350,70));
              table.getColumnModel().getColumn(0).setPreferredWidth(150);
              table.getColumnModel().getColumn(1).setPreferredWidth(80);
              table.getColumnModel().getColumn(2).setPreferredWidth(80);
              table.getColumnModel().getColumn(3).setPreferredWidth(80);
              table.getColumnModel().getColumn(4).setPreferredWidth(80);
              table.getColumnModel().getColumn(5).setPreferredWidth(80);
              table.getColumnModel().getColumn(6).setPreferredWidth(90);
              table.getTableHeader();
              JScrollPane sp = new JScrollPane(table);
              east.add(quote);
              east.add(table);
              east.add(sp);
              sp.getViewport().add(table);
              add(east, BorderLayout.EAST);     
         public void doWside()
              left = new JPanel (new GridLayout(3, 1));
              inlabel = new JLabel("Enter Amount:", JLabel.RIGHT);
              outlabel = new JLabel("Enter Password to Display Information ", JLabel.RIGHT);
             result = new JLabel("Information (ENTER PASSWORD):  ", JLabel.RIGHT);
             left.setBackground(Color.WHITE);
             left.add(inlabel);
             left.add(outlabel);
             left.add(result);
              add( left, BorderLayout.WEST );
         public void doCenter()
             middletop = new JPanel( new GridLayout(3,3));
              moneyinput = new JTextField("$0.00",5);
              moneyinput.addActionListener(this);
             butimg = getImage( getCodeBase(), "button_1.gif");
              input = new JButton( new ImageIcon( butimg ));
              input.setForeground(Color.WHITE);
              input.setBorderPainted( false);
              input.setContentAreaFilled( false);
              input.setFocusPainted( false );
              input.setToolTipText("Select to input amount" );
              input.setFont(new Font("Serif", Font.BOLD, 17));
              input.addActionListener(this);
              clear = new JButton("ENTER");
              clear.addActionListener(this);
              clear.setActionCommand(Enter);
              pass = new JPasswordField(10);
              pass.setActionCommand(Enter);
              pass.addActionListener(this);
              information = new JLabel ("<HTML><FONT SIZE=-2>*********</FONT>", JLabel.CENTER);
              cleartable = new JButton("Clear Spreadsheet");
              middletop.setBackground(Color.WHITE);
              middletop.add(moneyinput);
              middletop.add(input);
              middletop.add(pass);
              middletop.add(clear);
              middletop.add(information);
              middletop.add(cleartable);
              add(middletop, BorderLayout.CENTER);
         public void actionPerformed(ActionEvent ae)
              String cmd = ae.getActionCommand();//password     
              /////////table
    ///////////ENTERAMOUNT///////////////////////////////////////////          
                   Object obj = ae.getSource();
                   if( obj == input )  
                        double d = Double.valueOf(moneyinput.getText()).doubleValue();
                        double output2 = (d/(7.38));
                        double a = d-output2;
                       NumberFormat nf = NumberFormat.getCurrencyInstance();
                        double rent = (a*(.45));
                        double utilities = (a*(.15));
                        double groceries = (a*(.10));
                        double clothes = (a*(.05));
                        double bills = (a*(.10));
                        double auto = (a*(.15));
    //HERE IS THE FOR LOOP WHERE I AM HAVING TROUBLE                 
                        for (int colindex=1; colindex<=6;colindex++)
                             table.setValueAt(nf.format(rent), 0, colindex);
                             table.setValueAt(nf.format(utilities), 1, colindex);
                             table.setValueAt(nf.format(groceries), 2, colindex);
                             table.setValueAt(nf.format(clothes), 3, colindex);
                             table.setValueAt(nf.format(bills), 4, colindex);
                             table.setValueAt(nf.format(auto), 5, colindex);
                        validate();
                        repaint();
                   //taxlabelsouth.setText(nf.format(output2));     
         

    Hello,
    *> >
    Each time a user inputs a selection, it is supposed to return values in the first column only. The next time a user inputs an amount, it should go into the next column, etc.
    As of now, the user inputs an amount and returns the values in all the columns (...)
    //HERE IS THE FOR LOOP WHERE I AM HAVING TROUBLE                 
                        for (int colindex=1; colindex<=6;colindex++)You are aware that this line iterates (loops) over all 6 columns, right? So it's kind of normal that all columns are updated...
    How do i get the column # to increase each time a user inputs an amount? thanks!To update only one column at a time, don't loop, instead keep a columnIndex as an instance variable (of the applet), and increase its value once each time you pass in this branch of code (don't loop).
    Make sure to handle wrapping the value (or whatever your business logic implies when you've filled all columns), as setting the value into a column that doesn't exist (colIndex>6) will likely throw an exception.
    N.B.:
                        validate();
                        repaint();validate() tells the applet to re-layout its children: this is not useful if you haven't added/removed/"resized" any children.
    repaint() tells the applet to repaint itslef. Only the Jtable needs to be repainted, IMHO, and I think a repaint() command is already done automatically during the setValue(...) call, so it's probably not necessary either.
    Hope this helps.
    Edited by: jduprez on Nov 23, 2009 11:35 AM

  • Quick for loop question

    Hi everybody,
    I have a feeling this is so obvious that I'm missing it, so if anyone would give me some advice, I'd appreciate it.
    I have a method with with three parameters that loops through them and progressively adds or subtracts them with a for loop, based on the order. The only way I can think of to do this, though, is with two for loops with almost identical code. I know there must be an easier way to do this, but I think I've been staring at it too long, can anyone give me a hand conceptually, please?
    The method is:
    private void create( int param1, int param2 ) {
            int entries = 5;
            double increment;
            if( param1 > param2 ) {
                increment = param1 - param2;
                for( int i = 0; i < entries; i++ ) {
                    System.out.println( param1 - ( i * increment ) );
            } else if( param2 > param1 ) {
                increment = param2 - param1;
                for( int i = 0; i < entries; i++ ) {
                    System.out.println( param1 + ( i * increment ) );
         }Thanks,
    Jezzica85
    Edited by: jezzica85 on Mar 30, 2009 2:38 PM

    private void create( int param1, int param2 ) {
        if( param1 > param2 ) {
            create(param2, param1);
        } else if( param2 > param1 ) {
            int entries = 5;
            double increment = param2 - param1;
            for(int i = 0; i < entries; i++ ) {
                System.out.println( param2 + (i * param1));
        } //equal do nothing?
    }or
    private void create2( int param1, int param2 ) {
        if (param1 != param2) {
            int entries = 5;
            int minParam = Math.min(param1, param2);
            int maxParam = Math.max(param1, param2);
            double increment = maxParam - minParam;
            for( int i = 0; i < entries; i++ ) {
                System.out.println( maxParam - (i * minParam));
      }

  • Adding a for loop.

    I need to add a for loop so that it displays all values less than 5.00. Also, I need to display all values that are above the average. Can anyone show me hoe to do this? Here is what I have so far.
    public class project
    public static void main(String[] args)
    double[] price = {1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00, 17.00, 18.00, 19.00, 20.00};
    double total = 0;
    for (int nums = 0; nums < price.length; ++nums)
    total += price[nums];
    System.out.println("The total is " + total);
    System.out.println("The average is " +total/(double)price.length);

    Add the following lines of code to your project.java:
    ave = total/(double)price.length;
    for(int i=0; i<price.length; i++){
    if(price[i] < 5 || price[i] < ave)
    System.out.println(price);
    now your project.java looks like,
    public class project
    public static void main(String[] args)
    double[] price = {1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00, 8.00, 9.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00, 17.00, 18.00, 19.00, 20.00};
    double total = 0, ave;
    for (int nums = 0; nums < price.length; ++nums)
    total += price[nums];
    ave = total/(double)price.length;
    for(int i=0; i<price.length; i++){
    if(price[i] < 5 || price[i] < ave)
    System.out.println(price[i]);
    System.out.println("The total is " + total);
    System.out.println("The average is " + ave);
    Is this what you want??

  • Please help with the FOR loop and the array..

    I was trying to place some words in the Movie Clip
    "TextPanel" and set a
    random position to each of them.
    But it's not working.
    1) I created a Movie Clip "word" and inside that MC I created
    a text field
    and gave it an identifier "textFiled".
    2) The linkage name for Movie Clip "word" I set to "word".
    3) In the actionscript I created an Array called "aWords".
    4) Then I created a FOR loop that should
    place (attach) Movie Clips "word0", "word1", "word2" and
    "word3" to the
    movie clip TextPanel, and set the textField text for each of
    them to the
    text from the Array.
    But the script attaches 4 Movie Clips with a name
    "Undefined", instead of 4
    different names (from the Array).
    What is wrong with this script?
    var aWords:Array = [apple,banana,orange,mango];
    for(i=0;i<aWords.length;i++){
    var v = TextPanel.attachMovie("word","word"+i,i);
    v.textFiled.text = aWords
    v._x = randomNumber(0,Stage.width);
    v._y = randomNumber(0,Stage.height);
    Thanks in advance

    But in my Post I already wrote v.textFiled.text = aWords
    so I don't understand what were you correcting..
    And one more:
    I have tested it by changing the
    v.textFiled.text = aWords; to v.textFiled.text = "some
    word";
    and it's working fine.
    So there is something wrong with the Array element, and I
    don't know why..
    "aniebel" <[email protected]> wrote in
    message
    news:ft2d5k$lld$[email protected]..
    > Change:
    > v.textFiled.text = aWords;
    >
    > to:
    > v.textFiled.text = aWords
    >
    > It needs to know which element inside the array you want
    to place in the
    > textfield (or textfiled) :)
    >
    > If that doesn't work, double check that your instance
    name is correct
    > inside
    > of "word".
    >

Maybe you are looking for

  • Problem with selectOneMenu in Datatable

    Hi I have the following datatable that binds correctly to a set of Game objects. I need to have a dropdown with the numbers 1 to 10 as items which is bound to each dataItem's newRating field. However there is some problem with the dropdown that i can

  • Optimum size for a full browser width image?

    Hi all, I'm pretty new to Muse and these forums (hello everyone!) and have been tinkering around with some features. I'm currently creating a website for my band that integrate a full width browser image at the top of each page. I was wondering what

  • Scroll with mouse scroller - possible?

    hello! i'm in desperate need!! for this website i'm helping in, the client wanted me to scroll this section with words AND images. so , i used the scroll pane component from Flash mx8. it works. but, now the client wants it to scroll faster when usin

  • Best way to import videos only for nested folders?

    I have a bunch of nested folders like this TOP LEVEL -> Day 1 ->->Videos ->->Photos -> Day 2 ->->Videos ->->Photos Day 69... Now I can't just choose import on the top level, because I don't want to import any of the photos. I don't want to click on e

  • Oracle EBS R12

    Oracle EBS R12 (12.1.3) / 11.1.0.7.0 Oracle Critical Patch Update Advisory - January 2013 How do we find whether the EBS users are suing SHA-1 password verifier? What does it means of SHA-1 password verifier? Thanks in advance