Recursive calculation on arrays

I have a 3x10 input array.
I take row 0, apply a high pass filter, take the log, and then plot it.
Second round I have another 3x10 array, and apply the same thing on row 0. (all running in a while loop)recursiv
So my plot would have 20 points, from row 0 (eventually I would do this for all 3 rows)
Is this different from if I pass it in a 3x20 array at once, and do the processing and then plot it?
Or is there a way I can save the plotted value on the graph, and just add the new result at the end?
I am trying to avoid saving all values, so I dont want to use the 3x20 array. I want to do the calculations on 3x10 chunks of data while getting the same results.
Thanks!!!!!!!!!

You seem to love the word "recursive" in all your questions, but I don't think it makes sense the way you use it. If the calculations are independent (sometimes they are not!), it does not matter if you do the calculations all at once or piecewise.
A 2x10 array is tiny. What is your actual concern?
Your description is very fuzzy. If you want to save historic values inside a graph, you should use a chart instead. Does this have anything to do with your earlier question?
LabVIEW Champion . Do more with less code and in less time .

Similar Messages

  • Recursive calculation problem

    Hi,
    I am getting 36 instead of 29 for the following program:
    import java.math.BigDecimal;
    import java.math.BigInteger;
    class TestRevenue
         public static void main(String[] args)
              System.out.println("Hello World!");
              TestRevenue testRevenue = new TestRevenue();
              testRevenue.start();
         private void start()
             System.out.println("start");
             CampaignRevenue preCampaignRevenue = new CampaignRevenue();
             CampaignRevenue campaignRevenue = new CampaignRevenue();
             CampaignRevenue postCampaignRevenue = new CampaignRevenue();
             preCampaignRevenue.setRecordsCount("5");
             campaignRevenue.setRecordsCount("15");
             postCampaignRevenue.setRecordsCount("9");
             campaignRevenue.addCampaignRevenue(preCampaignRevenue);
             campaignRevenue.addCampaignRevenue(postCampaignRevenue);
             BigInteger postRecordsCount = campaignRevenue.getRecordsCount();
             System.out.println("postRecordsCount=" + postRecordsCount);         
    import java.math.BigDecimal;
    import java.math.BigInteger;
    public class CampaignRevenue implements java.io.Serializable
        private static String totalEarnedRevenue = "0.00"; //NOI18N
        private static String totalRenewalRateRevenue = "0.00"; //NOI18N
        private static String recordsCount = "0"; //NOI18N     
         public void setTotalEarnedRevenue(String setTotalEarnedRevenue)
              totalEarnedRevenue = setTotalEarnedRevenue;
         public void setTotalRenewalRateRevenue(String setTotalRenewalRateRevenue)
              totalRenewalRateRevenue = setTotalRenewalRateRevenue;
         public void setRecordsCount(String setRecordsCount)
              recordsCount = setRecordsCount;
         public CampaignRevenue addCampaignRevenue(CampaignRevenue campaignRevenue)
              CampaignRevenue retCampaignRevenue = new CampaignRevenue();
              retCampaignRevenue.setRecordsCount((getRecordsCount()
                        .add(campaignRevenue.getRecordsCount())).toString());
              retCampaignRevenue.setTotalEarnedRevenue((getTotalEarnedRevenue()
                        .add(campaignRevenue.getTotalEarnedRevenue())).toString());
              retCampaignRevenue.setTotalRenewalRateRevenue((getTotalRenewalRateRevenue()
                        .add(campaignRevenue.getTotalRenewalRateRevenue())).toString());
              return retCampaignRevenue;
        public BigDecimal getTotalEarnedRevenue()
             if (totalEarnedRevenue != null)
                  return new BigDecimal(totalEarnedRevenue);
             else
                  return new BigDecimal(0.00);
        public BigDecimal getTotalRenewalRateRevenue()
             if (totalRenewalRateRevenue != null)
                  return new BigDecimal(totalRenewalRateRevenue);
             else
                  return new BigDecimal(0.00);
        public BigInteger getRecordsCount()
             if (recordsCount != null)
                  return new BigInteger(recordsCount);
             else
                  return new BigInteger("0"); // NOI18N
    }May I know where went wrong ?
    Thank you in advance.
    et

    Hi,
    Thanks for all the suggestion, my objective is to sum all the values passed in from different instances.
    I had changed to a pair of static and non-static variable, the former is for retaining the previous value for summation purpose. And finally, the recursive calculation works. Here is the amended programs:
    import java.math.BigDecimal;
    import java.math.BigInteger;
    class TestRevenue
         public static void main(String[] args)
              System.out.println("Hello World!");
              TestRevenue testRevenue = new TestRevenue();
              testRevenue.start();
         private void start()
             System.out.println("start");
             BigInteger resultRecordsCount;
             BigDecimal resultEarnedRevenue;
             BigDecimal resultRenewalRateRevenue;
             CampaignRevenue preCampaignRevenue = new CampaignRevenue();
             CampaignRevenue campaignRevenue = new CampaignRevenue();
             CampaignRevenue postCampaignRevenue = new CampaignRevenue();   
            CampaignRevenue resultCampaignRevenue = new CampaignRevenue();
             preCampaignRevenue.setRecordsCount("5");
             preCampaignRevenue.setTotalEarnedRevenue("1000.00");
             preCampaignRevenue.setTotalRenewalRateRevenue("2000.00");
             campaignRevenue.setRecordsCount("15");
             campaignRevenue.setTotalEarnedRevenue("2000.00");
             campaignRevenue.setTotalRenewalRateRevenue("3000.00");
             postCampaignRevenue.setRecordsCount("9");
             postCampaignRevenue.setTotalEarnedRevenue("3000");
             postCampaignRevenue.setTotalRenewalRateRevenue("4000.00");
             resultCampaignRevenue.addCampaignRevenue(preCampaignRevenue);
             resultRecordsCount = resultCampaignRevenue.getRetRecordsCount();
             resultEarnedRevenue = resultCampaignRevenue.getRetTotalEarnedRevenue();
             resultRenewalRateRevenue = resultCampaignRevenue.getRetTotalRenewalRateRevenue();
             System.out.println("1. resultRecordsCount=" + resultRecordsCount); //NOI18N  
             System.out.println("1. resultEarnedRevenue=" + resultEarnedRevenue); //NOI18N   
             System.out.println("1. resultRenewalRateRevenue=" + resultRenewalRateRevenue); //NOI18N   
             resultCampaignRevenue.addCampaignRevenue(campaignRevenue);
             resultRecordsCount = resultCampaignRevenue.getRetRecordsCount();
             resultEarnedRevenue = resultCampaignRevenue.getRetTotalEarnedRevenue();
             resultRenewalRateRevenue = resultCampaignRevenue.getRetTotalRenewalRateRevenue();         
             System.out.println("2. resultRecordsCount=" + resultRecordsCount); //NOI18N  
             System.out.println("2. resultEarnedRevenue=" + resultEarnedRevenue); //NOI18N   
             System.out.println("2. resultRenewalRateRevenue=" + resultRenewalRateRevenue); //NOI18N   
             resultCampaignRevenue.addCampaignRevenue(postCampaignRevenue);
             resultRecordsCount = resultCampaignRevenue.getRetRecordsCount();
             resultEarnedRevenue = resultCampaignRevenue.getRetTotalEarnedRevenue();
             resultRenewalRateRevenue = resultCampaignRevenue.getRetTotalRenewalRateRevenue();            
             System.out.println("3. resultRecordsCount=" + resultRecordsCount); //NOI18N
             System.out.println("3. resultEarnedRevenue=" + resultEarnedRevenue); //NOI18N   
             System.out.println("3. resultRenewalRateRevenue=" + resultRenewalRateRevenue); //NOI18N             
    import java.math.BigDecimal;
    import java.math.BigInteger;
    public class CampaignRevenue implements java.io.Serializable
         public String totalEarnedRevenue = "0.00"; //NOI18N
         public static String retTotalEarnedRevenue = "0.00"; //NOI18N
        public String totalRenewalRateRevenue = "0.00"; //NOI18N
        public static String retTotalRenewalRateRevenue = "0.00"; //NOI18N
        public String recordsCount = "0"; //NOI18N     
        public static String retRecordsCount = "0"; //NOI18N     
         public void setTotalEarnedRevenue(String setTotalEarnedRevenue)
              totalEarnedRevenue = setTotalEarnedRevenue;
         public void setRetTotalEarnedRevenue(String setRetTotalEarnedRevenue)
              retTotalEarnedRevenue = setRetTotalEarnedRevenue;
         public void setTotalRenewalRateRevenue(String setTotalRenewalRateRevenue)
              totalRenewalRateRevenue = setTotalRenewalRateRevenue;
         public void setRetTotalRenewalRateRevenue(String setRetTotalRenewalRateRevenue)
              retTotalRenewalRateRevenue = setRetTotalRenewalRateRevenue;
         public void setRecordsCount(String setRecordsCount)
              recordsCount = setRecordsCount;
         public void setRetRecordsCount(String setRetRecordsCount)
              retRecordsCount = setRetRecordsCount;
         public CampaignRevenue addCampaignRevenue(CampaignRevenue campaignRevenue)
              BigInteger getRetRecordsCount = getRetRecordsCount();
              BigDecimal getRetTotalEarnedRevenue = getRetTotalEarnedRevenue();
              BigDecimal getRetTotalRenewalRateRevenue = getRetTotalRenewalRateRevenue();
              CampaignRevenue retCampaignRevenue = new CampaignRevenue();
              retCampaignRevenue.setRetRecordsCount((getRetRecordsCount
                        .add(campaignRevenue.getRecordsCount())).toString());
              retCampaignRevenue.setRetTotalEarnedRevenue((getRetTotalEarnedRevenue()
                        .add(campaignRevenue.getTotalEarnedRevenue())).toString());
              retCampaignRevenue.setRetTotalRenewalRateRevenue((getRetTotalRenewalRateRevenue()
                        .add(campaignRevenue.getTotalRenewalRateRevenue())).toString());
              return retCampaignRevenue;
        public BigDecimal getTotalEarnedRevenue()
             if (totalEarnedRevenue != null)
                  return new BigDecimal(totalEarnedRevenue);
             else
                  return new BigDecimal(0.00);
        public BigDecimal getRetTotalEarnedRevenue()
             if (retTotalEarnedRevenue != null)
                  return new BigDecimal(retTotalEarnedRevenue);
             else
                  return new BigDecimal(0.00);
        public BigDecimal getTotalRenewalRateRevenue()
             if (totalRenewalRateRevenue != null)
                  return new BigDecimal(totalRenewalRateRevenue);
             else
                  return new BigDecimal(0.00);
        public BigDecimal getRetTotalRenewalRateRevenue()
             if (retTotalRenewalRateRevenue != null)
                  return new BigDecimal(retTotalRenewalRateRevenue);
             else
                  return new BigDecimal(0.00);
        public BigInteger getRecordsCount()
             if (recordsCount != null)
                  return new BigInteger(recordsCount);
             else
                  return new BigInteger("0"); // NOI18N
        public BigInteger getRetRecordsCount()
             if (retRecordsCount != null)
                  return new BigInteger(retRecordsCount);
             else
                  return new BigInteger("0"); // NOI18N
    }Regards,
    ET.

  • Avarage calculation with array

    hello i have the labview 8.5
    an i must measure the temperature,,,,
    with the labview i must:
    with DAQ-assistent take the datas an show (every second (1hz)) it.......
     i must also take the avarage from the last 60 datas (1min) and save it in a excel file....i thought i take the 60datas in a for loop wire it in an array and then divide it through 60
    CAN SOMEBODY HELP ME PLEASE

    Hi,
    here there is the link to an example that acquires data and writes them in an Excel file in tablature and graph form:
    http://zone.ni.com/devzone/cda/epd/p/id/25
    In attachment there is an example about how to do the running average.
    Regards,
    Serena
    Applications Engineering
    National Instruments
    Attachments:
    Calculate Running Average.vi ‏16 KB

  • Do the custom rollup member formulas work recursively for parent child dimension?

    Hi
    We have custom rollup set up for Account dimension which is parent child.
    It seems to work fine when the custom member formula refers to a base account member i.e. if the formula for MemberKey4 is (MemberKey1 + MemberKey2) then it shows the sum of the underlying members 1 and 2.
    But if the formula for MemberKey10 is (MemberKey3 + MemberKey4) then it should evaluate the value for MemberKey4 first and then add to it value for MemberKey3 to come up with final number for MemberKey10.
    Do the custom rollup work fine with the recursive calculations? Is this recursion limited to some level?
    Thanks
    Shailesh

    Hi Jorg,
    Thanks for your input.
    Actually the hierarhcy is more determined by the parent child relationship. So we cannot move the members as per the formula. And further the formulas are not always additive, there are divisions and multiplactions happening also.
    Further the calculated members (account members) are used in different places, the usage level of calculated members could be 3 in some cases i.e. MemberKey15 = (calculated using MemberKey10 = (calculated using MemberKey7 = (Calculated using MemberKey4 = (calculated using base members)))). Now inserting the base members in place of a calcuated member becomes more of string manipulation.
    And on the top of above complexity, the formulas are not static and they are more user defined, they may change between time periods, which forces us to write a dynamic procedure to translate the 'business formula' into SSAS formula. We expect the custom rollup to work as expected (i.e. if the formula contains a calculation involving the calculated member, it should resolve that first and so on) and we have written generic procedure to replace the Account Code in the 'business formula' with the accont key value with the account hierarchy char string.
    In the link http://doc.ddart.net/mssql/sql2000/html/olapdmad/agmdxadvanced_6jn7.htm for AS2000, it talks about the calculation pass deapth, it says:
    .......If a cube has custom rollup formulas or custom rollup operators, a second calculation pass is performed to handle the computations needed to calculate these features.......
    Now from the above, it is obvious that the OLAP engine will automatically go into recursion if the formula contains a cacluated member and it knows that the calculated member has to be resolved first before calculating the final formula result. The above article also talks about 'Calculation Pass Number' property in the AdvanceCube Editor (AS2000), which can be set to the value depending on the expected number of passes required in a given scenario. I don't find such an equivalent peoperty for SSAS 2005.
    Would anybody please throw some more ideas / insights on this issue?
    Jorg, thanks  again for your input...
    Shailesh

  • Multiplying elements of two different arrays

    hey, I have a while loop thats performing two separate operations similtaneously and filling the data elements of two different 1d arrays with data.with each iteration of the loop a new value pass from an operation to an array.
    I need to multipy to corresponding elements of the arrays such the first element of one array is skipped. so element i0 * element j1 , element i1 * elemnent j2 etc. how can i acess the elements and make the calculations? arrays could have hundreds of elements.
    Thanks.
    Brendan

    blue silver wrote:
    hi Peter,
    I have an array of 2,000,000 values (each long int). I need to do an "Moving average" operation which would than:
    1) takes average of the first 10 values , plots it
    2) remove the first value ,add 11.th value, take average, plots it in the next 100 ms in the chart
    3) remove the first value, add 12.th value, take average, plots it in the next 100 ms in the chart
    (as you see , it is a kind of shifting) the averaged array elements is always 10 , and after averaging those 10 elements , plot it with 100 ms distance in the graph.
    1999989)  remove the 1,999,989 th element , add the last element
    you have a possible idea ?
    your help will be tremendously appreciated.
    Regards
    Silver
    Try this.  It iterates 10 times taking a subset of the array each time to sum it to a shift register.  When done, divides by the total number of iterations.  So it adds i0 to i1 to i2 to i3 to i{N}.  For each element from i0 up.  It will give you an array where n elements are missing  (because elements 0 through n-1 don't have N samples to average to.
    Message Edited by Ravens Fan on 11-26-2007 09:26 PM
    Attachments:
    Example_BD.png ‏4 KB

  • Can anyone explain the array-binary implementation?

    Hi,
    i have a final exam tomorrow, and I got stuck on the array implementation of a binary tree, can anyone please provide me a code that implements the tree non recursively into an array, the book has a recursive code, which i tried to trace, but it got so deep and confusing. Can anyone please help?
    thanks :)
    Edited by: haraminoI on Apr 8, 2009 11:36 PM

    Melanie_Green wrote:
    haraminoI wrote:
    Hi,
    i have a final exam tomorrow, and I got stuck on the array implementation of a binary tree, can anyone please provide me a code that implements the tree non recursively into an array, the book has a recursive code, which i tried to trace, but it got so deep and confusing. Can anyone please help? Ehhh you could find an implementation online.
    Just remember given an array indexed from 0.
    Each indexes left child is (index*2+1), right child is (index*2+2).
    Each indexes parent is ((index-1)/2)
    Melthanks, i tried searching online, but i kept getting the recursive implementation.
    And now i see where to place the binary node and children values in the array, but how do I get the binary tree values from a sorted list in the frist place, thanks! :)

  • Acrobat Pro Calculating form fields lose functionality after enabling document for Reader

    I have a problem that continues to come up increasingly. I thought I had found a work-around on some forums, but it is still causing trouble. Im hoping you can answer the question.
    I am creating a form that requires simple calculations (sum and add). I can get these calculations to work just fine. However, as soon as I enable the document for Adobe Reader, the form seems to get amnesia. It loses the ability to calculate. When I go into the fields again to look at them, they still show that they are supposed to calculate, but arent working. I have to clear the calculations and completely reset them all in order to get them to function again, but as soon as I save this enabled doc, it loses its functionality all over again.
    Frustrating.
    I did find a work-around on a forum, but have only gotten it to work once. It had something to do with closing and saving the document, then reopening it before entering the calculations.
    Is there a clear-cut solution to this problem? The forums were rife with people experiencing the same frustrations.
    Thanks ahead of time for your assistance.

    Nathan,
    It's fairly straighforward to set up a custom validation script for this, but it might not be immediately obvious how to do it. I'll use your form as an example. In it, you have a number of rows with a Quantity field where the user enters how many items are needed, a Price field that has as its default value the price for the item, and a Total field which is a calculated field and should be the product of the Quantity and Price fields. The only variable in the calculation is the value of the Quantity field, so this will be easy.
    The Validate event of a field gets triggered when the field value is committed. This happens when the user enters a value and presses Enter, Tab, clicks outside of the field, etc. What the script should do is take the value the user entered, multiply it by the value that's in the Price field, and set the value of the Total field. The script could look something like:
    (function () {
        // Get the value of this field, as a number
        var qty = +event.value;
        // Get the value of the Price field, as a number
        var price = +getField("PRICE.0").value;
        // Calculate the total
        var total = qty * price;
        // Set the value of the Total field if not zero,
        // otherwise, blank it out
        getField("TTL.0").value = total ? total : "";
    What you really should do, however, is set up a document-level JavaScript (Advanced > Document Processing > Document JavaScripts...) that contains a function you can call from the QTY field of each row. The function will determine which row should be affected based on the field name that triggers it. Something like:
    function calcTotal() {
        // Get the row number from the field name
        // of the field that called this function
        var row = event.target.name.split(".").pop();
        // Get the value of the field that called this function, as a number
        var qty = +event.value;
        // Get the value of the Price field, as a number
        var price = +getField("PRICE." + row).value;
        // Calculate the total
        var total = qty * price;
        // Set the value of the Total field if not zero,
        // otherwise, blank it out
        getField("TTL." + row).value = total ? total : "";
    Than all you have to place as the custom Validate script of each of your QTY fields is the following:
    calcTotal();
    Also, make sure that you remove any calculations that you've set up on the Calculate tab of each TOTAL field. Now that the total fields do not rely on automatic calculations, it does not matter that the document is missing its field calculation order array, though this bug REALLY needs to be fixed. You should consider reporting it to Adobe. I will report it too.
    Note that this code assumes the QTY and PRICE fields are numeric fields, meaning they will either be blank or contain a valid number. You've ensured this by setting up each with a Format category of Number.
    George

  • Motion Assistant Contour Array Points - Optimal Array Size?

    I am working with the NI Motion Assistant API and plyaing around with the Contour Move generation where I feed a set of X, Y target points to the Set Contour Move Properties.
    One of the inputs is Profile Calculation Constraint - Array Size, Constraint Value (which would be the array size to use).
    I am wondering if there is a way to calculate the "optimal" array size for any particular move?  I know I can have too few - can I have too many points in an array (being reasonable here and not planning to use the whole 2^32 size allowed).
    Thanks.
    Ryan Vallieu
    Automation System Architect

    Hi Ryan,
    Unfortunately, I'm not so sure I have a good answer for you. I'll evaluate some of the pros and cons below and then ultimately make a recommendation:
    Constraint Type: Array Size
    Pros
    You always have a fixed sized array of setpoints. If you are using a 73xx card, this simplifies setting up your contour buffer. It also avoids using a lot of memory.
    Cons
    For long moves, you could have a long time and large distance between position setpoints. The motion card will do a spline interpolation to smooth the move, but the splining algorithm is only so good.
    If you are sending the contour setpoints to a motion card, you don't know the interval between setpoints (although this isn't difficult to obtain).
    Constraint Type: Sampling Time
    Pros
    Regardless of the move, you always have a fixed time between setpoints. As long as your sampling time isn't too large, even fast moves should execute accurately.
    Cons
    For a long move, you could generate a lot of setpoints that consume a lot of memory.
    Setting up contouring buffers can be trickier.
    Conclusion
    It depends on what you expect the end customer to be doing. I prefer using the sampling time constraint since it is more robust for fast, long moves (and still good for slow, short moves). It will make creating contour buffers more difficult, but there is an example (Two-Axis Smart Contouring.vi) that shows how to dynamically update the buffer. Ultimately, I think it is better to focus on accurate moves than minimizing memory consumption.
    If you decide to go with the sampling time method, I would start with a constraint value of .01, since 10msec is the shortest interval when configuring a contour buffer. Try and generate some position profiles to see how big the arrays are. For optimizing, it is just a tradeoff between array size and the accuracy of the generated motion profile.
    Thanks,
    Paul B.
    Motion Control R&D

  • Wrong path when zip a file

    When I try to Zip a file(backup.zip) everything is good except one thing.
    When I use WinZip to unzip the file, the path for the file contains all subdirectories eg. c:\mycatalog\backup\db\data.data
    I would like the path to be like: backup\db\data.data
    The code:
    pathName is "c:\mycatalog"
    fileName is "backup"
    public class Zip {
    private static ZipOutputStream zos;
    * Creates a Zip archive. If the name of the file passed in is a
    * directory, the directory's contents will be made into a Zip file.
    public static void makeZip(File pathName, String fileName)
    throws IOException, FileNotFoundException
    File file = new File(pathName,fileName);
    zos = new ZipOutputStream(new FileOutputStream(pathName.toString()+"\\"+fileName+".lum"));
    //Call recursion.
    recurseFiles(file);
    //We are done adding entries to the zip archive,
    //so close the Zip output stream.
    zos.close();
    * Recurses down a directory and its subdirectories to look for
    * files to add to the Zip. If the current file being looked at
    * is not a directory, the method adds it to the Zip file.
    private static void recurseFiles(File file)
    throws IOException, FileNotFoundException
    if (file.isDirectory()) {
    //Create an array with all of the files and subdirectories
    //of the current directory.
    String[] fileNames = file.list();
    if (fileNames != null) {
    //Recursively add each array entry to make sure that we get
    //subdirectories as well as normal files in the directory.
    for (int i=0; i<fileNames.length; i++) {
    recurseFiles(new File(file, fileNames));
    //Otherwise, a file so add it as an entry to the Zip file.
    else {
    byte[] buf = new byte[1024];
    int len;
    //Create a new Zip entry with the file's name.
    ZipEntry zipEntry = new ZipEntry(file.toString());
    //Create a buffered input stream out of the file
    //we're trying to add into the Zip archive.
    FileInputStream fin = new FileInputStream(file);
    BufferedInputStream in = new BufferedInputStream(fin);
    zos.putNextEntry(zipEntry);
    //Read bytes from the file and write into the Zip archive.
    while ((len = in.read(buf)) >= 0) {
    zos.write(buf, 0, len);
    //Close the input stream.
    in.close();
    //Close this entry in the Zip stream.
    zos.closeEntry();

    Sorry, I want the path to be like: "\db\data.data"

  • New to java, please help me :(

    hi, i have to complete a BMI calculator with arrays and switch, i need it so that if input a / b is selected it will calculate metric / imperial (i know that both calcs are the same, its just a placeholder for the time being). once thats selected users are asked to input name, age, height and weight, then looped again for another user to input into the array.
    once completed the name and age along with the BMI calculation for all the users that have inputted are displayed
    the problem is, the calculations are wrong, where it should be outputting a BMI of between 20-23ish im getting 0.3
    i think i had this problem when i done the switch example previously, but to fix that i just lumped all the code (inputs and calcs) into each case. in this method im guessing that would be an incorrect approach ?
    btw, sorry for my layout, ive been debugging for ages now and havnt had time to clean it up :/
    thank you in advance and heres my code:-
    package bmicalculationex;
    import javax.swing.*;
    public class Main {
    public static void main(String[] args) {
    String output;
    double Hfeet=0, Wstone=0, Hinches=0, Wlbs=0;
    String Hfeetstr, Wstonestr, Hinchesstr, Wlbsstr, age;
    String name;
    double bmiweight=0, bmiheight=0, BMI=0;
    Item[] myItemArray = new Item[2];
    for(int i = 0;i<2;i++){
    myItemArray[i] = new Item();
    String input = JOptionPane.showInputDialog(
    "Welcome to Chunks BMI calculator\n"+
    "a) Metric.\n"+
    "b) Imperial\n"+
    "q) Quit\n"+
    "\nPlease enter letter code" );
    char code = input.charAt(0);
    switch(code){
    case 'a':
    output= "Imperial.";
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    break;
    case 'b': output= "Metric.";
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    break;
    default: output= "Error.";
    JOptionPane.showMessageDialog(null,"Invalid Selection.\n"+ "Please try again.");
    JOptionPane.showMessageDialog(null, "You have selected :- " + output + "\n\n" +" Thank you.");
    //User In-
    for(int c=0;c<2;c++){
    name = JOptionPane.showInputDialog("enter your name");
    age = JOptionPane.showInputDialog("enter your age");
    Hfeetstr = JOptionPane.showInputDialog("enter your Height");
    Hinchesstr = JOptionPane.showInputDialog("enter the remainder");
    Wstonestr = JOptionPane.showInputDialog("enter your weight");
    Wlbsstr = JOptionPane.showInputDialog("enter the remainder");
    Hfeet = Float.parseFloat(Hfeetstr);
    Wstone = Float.parseFloat(Wstonestr);
    Hinches = Float.parseFloat(Hinchesstr);
    Wlbs = Float.parseFloat(Wlbsstr);
    bmiweight = Wstone + Wlbs;
    bmiheight = Hinches + Hfeet;
    BMI = bmiweight / (bmiheight*bmiheight);
    myItemArray[c].setname(name);
    myItemArray[c].setyear(age);
    myItemArray[c].setBMII(BMI);
    String message = "";
    for(int n=0;n<2;n++){
    message = message + "Name :- " + myItemArray[n].getname() + " " + "Age :- " + " " + myItemArray[n].getaged() + "BMI :- " + " " +myItemArray[n].getBMI() +"\n";
    JOptionPane.showMessageDialog(null, message);
    }//end of main method
    }//end of main class
    class Item{
    private String namea;
    private String agea;
    private double BMIa;
    public Item(){
    agea = "";
    BMIa = 0;
    namea = "";
    public Item(String nameb, String ageb, double BMIb){
    namea = nameb;
    agea = ageb;
    BMIa = BMIb;
    public String getname(){
    return namea;
    public String getaged(){
    return agea;
    public double getBMI(){
    return BMIa;
    public String setname (String nameb){
    namea = nameb;
    return nameb;
    public void setyear(String ageb){
    agea = ageb;
    public void setBMII(double BMIb){
    BMIa = BMIb;
    }

    yush !
    i done it :D
    i just ended up lumping all the code into each case like i did last time, as when i had the calculations outside of the cases it wasnt taking the values from inside the case. nevermind....
    another problem i do have though, i need a loop so that once the program finishes it repeats itself until an X is entered, im not very good with loops :S
    i tend to try it like this
    quit = 1;
    while (quit<2){
    then just have one of the cases as quit +1
    so in mine it looks liek this:
    int quit=1;
    while (quit<2){
    String input = JOptionPane.showInputDialog(
    "Welcome to Chunks BMI calculator\n"+
    "a) Metric.\n"+
    "b) Imperial\n"+
    "q) Quit\n"+
    "\nPlease enter letter code" );
    char code = input.charAt(0);
    switch(code){
    case 'a':
    JOptionPane.showMessageDialog(null, "You have selected imperial. "+"\n\n" +" Thank you.");
    for(int c=0;c<2;c++){
    name = JOptionPane.showInputDialog("enter your name");
    age = JOptionPane.showInputDialog("enter your age");
    Hfeetstr = JOptionPane.showInputDialog("enter your Height in feet");
    Hinchesstr = JOptionPane.showInputDialog("enter the remaining inches");
    Wstonestr = JOptionPane.showInputDialog("enter your weight in stone");
    Wlbsstr = JOptionPane.showInputDialog("enter the remaining lbs");
    Hfeet = Float.parseFloat(Hfeetstr);
    Wstone = Float.parseFloat(Wstonestr);
    Hinches = Float.parseFloat(Hinchesstr);
    Wlbs = Float.parseFloat(Wlbsstr);
    Wlbs = Wlbs * 0.45359237;
    Hinches = Hinches * 0.0254;
    Hfeet = Hfeet * 0.3048;
    Wstone = Wstone * 6.35029318;
    bmiweight = Wstone + Wlbs;
    bmiheight = Hinches + Hfeet;
    BMI = bmiweight / (bmiheight*bmiheight);
    String cat="";
    if (BMI <18.5) cat = ("Posh spice");
    else if (BMI >= 18.5 && BMI <=25) cat = ("Fit !");
    else if (BMI >25 && BMI <=30) cat = ("Fatty !");
    else if (BMI >30)cat = ("Super Fatty");
    myItemArray[c].setcat(cat);
    myItemArray[c].setname(name);
    myItemArray[c].setyear(age);
    myItemArray[c].setBMII(BMI);
    break;
    case 'b': output= "Metric.";
    etc.....
    this is causing me the problems:
    for(int i = 0;i<2;i++){
    myItemArray[i] = new Item();
    says a non static variable cannot be referenced from a static context, i know im being stupid with my implementation, but whats a better way ?
    thanks again :)
    Edited by: Clunk on Nov 17, 2008 4:05 PM

  • Anyone got a zip-tip?

    When I try to Zip a file(backup.zip) everything is good except one thing.
    When I use WinZip to unzip the file, the path for the file contains all subdirectories eg. c:\mycatalog\backup\db\data.data
    I would like the path to be like: db\data.data
    The code:
    pathName is "c:\mycatalog"
    fileName is "backup"
    public class Zip {
    private static ZipOutputStream zos;
    * Creates a Zip archive. If the name of the file passed in is a
    * directory, the directory's contents will be made into a Zip file.
    public static void makeZip(File pathName, String fileName)
    throws IOException, FileNotFoundException
    File file = new File(pathName,fileName);
    zos = new ZipOutputStream(new FileOutputStream(pathName.toString()+"\\"+fileName+".lum"));
    //Call recursion.
    recurseFiles(file);
    //We are done adding entries to the zip archive,
    //so close the Zip output stream.
    zos.close();
    * Recurses down a directory and its subdirectories to look for
    * files to add to the Zip. If the current file being looked at
    * is not a directory, the method adds it to the Zip file.
    private static void recurseFiles(File file)
    throws IOException, FileNotFoundException
    if (file.isDirectory()) {
    //Create an array with all of the files and subdirectories
    //of the current directory.
    String[] fileNames = file.list();
    if (fileNames != null) {
    //Recursively add each array entry to make sure that we get
    //subdirectories as well as normal files in the directory.
    for (int i=0; i<fileNames.length; i++) {
    recurseFiles(new File(file, fileNames));
    //Otherwise, a file so add it as an entry to the Zip file.
    else {
    byte[] buf = new byte[1024];
    int len;
    //Create a new Zip entry with the file's name.
    ZipEntry zipEntry = new ZipEntry(file.toString());
    //Create a buffered input stream out of the file
    //we're trying to add into the Zip archive.
    FileInputStream fin = new FileInputStream(file);
    BufferedInputStream in = new BufferedInputStream(fin);
    zos.putNextEntry(zipEntry);
    //Read bytes from the file and write into the Zip archive.
    while ((len = in.read(buf)) >= 0) {
    zos.write(buf, 0, len);
    //Close the input stream.
    in.close();
    //Close this entry in the Zip stream.
    zos.closeEntry();

    http://forum.java.sun.com/thread.jsp?forum=31&thread=408815
    Found with
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Bzip%2C+%2B%22relative+path%22&col=javaforums

  • Trajectory program event handling

    Nobody else responded to my question on the subject "Trajectory" in Java Programming forum. See my post history for problem description and code. Perhaps the subject is more appropriate here as an event handling issue. Who has the technical savvy to attempt a solution?

    (2) I wouldn't have problem with separate classes as
    long as I have no inner classes and the program
    essentially works. Sure, one 10,000 - line class may also work fine. However, it is reccommended do not make classes
    (as well as source files) very large. The reason is that long file is more difficult to debug.
    Second reason why i advised you to do that is that you mix in one class Trajectory (which is about 2000 lines long!!!) all - interface, event handling, calculations, parts responsible for 2D panel processing....
    Well, this is not Java is supoposed to be used for.
    (3) Creating object of class Falling object is
    something I'll consider. If you could show me a brief
    code example, I'll understand more.
    class fallingObject
          private double mass;
          private double speed;
          Position[] trajectory = new Position[1000];  // Create class Position each object of which holds only
          // 2 variables - x and y
         //all initial data related to this object
         fallingObject(double mass, double speed , /* the rest ........*/)
              this.mass = mass;
               this.speed = speed;
              moveObject();
              //and so on
        // some methods you need
         private moveObject ()
             // perform all calculations
             // fill array
         // etc
    Now, because all except trajectory array and constructor is private you cannot change this object outside
    class. This means that if something goes wrong with calculations, you check only this class and nothing else. In your case you can change some variable at lines 1352 and 122 - you have to check all program to find bug. Here you have to check only this class.
    You may also supply this class with mutators and accessors
    public double getMass()
       return mass;
    public void setMass(double mass) // only if you really need this
       this.mass = mass;
    The time interval
    is a tricky parameter since not all calculations work
    properly with input data; check input
    the logic would require more
    complexity and possibly cause run time problems;
    automatically testing for the appropriate time
    interval could also reduce program efficiency. Dont think so. You can calculate time of falling and divide it by 1000, for instance.
    It will take very short time.
    I don't
    want to set a limit for array points to 1000 or less
    since the precision becomes limited and the power of
    the program can be hurt severely since the time
    duration would be restricted to less than 16 2/3
    minutes( 1 second per array index increment). Dont use real time simulation. There is no sence in it. You just want to show how object is falling.
    Also, I
    don't think the array size can't be changed during a
    program run although I have set a much higher maximum
    value for array size. Theres no need to change array size.
    (4) Erasing data from textfields is something I desire
    as a calculation reset feature since it should signal
    user that it expects new data and not looking at old
    data; however, I might consider additional variables
    to hold the data. Well, man, it was quite irritating to type them in. So many fields. User is not stupid,
    he knows that he can input other data. Almost anybody will leave this page and wont want to
    fill fields again. You have to think about user, not about what you want.
    (5 )BTW, what I have in the array doesn't have the
    same precision as with the calculation mode. The 2D
    simulation uses less precise data to become visually
    practical for comprehension of users. But perhaps I
    need more than one type of array, but then again,
    performance could be a problem.
    (6) I thought the program already does take parameters
    from text fields and start again. This is what I
    desire anyway so I'm not sure why I need new start
    feature.
    (7) Restart animation seems unaccepatble since I
    prefer to treat each simulation as something based on
    new calculation data.
    I would have initially set up the program with OOD
    emphasis, but the original intent was a java
    conversion of a a C++ program that needed only a
    structured program design and the conversion worked
    fine. This Java program has evolved with the 2D
    simulation enhancements.
    When you did testing the other day, did you use
    appletviewer? I looked at it on your site using Safari and run it as application also.
    Appletviewer will not detect the problem
    so don't rely on Appletviewer to interpret the
    problem. Oddly, I wish the program behaved the same
    way as what happens when using appletviewer. In fact,
    if I could change 2d reset button logic to terminate
    and restart the entire applet again via html, then my
    problem would be solved. But I don't know if this type
    of applet restart is possible or how to effect the
    code change if feasible.

  • Image Moment - Optimizing Code for Speed

    Hello 
    I'm want to find the moment of inertia of an 2d-array. The array is converted from an image using "IMAQ ImageToArray".
    The algorithm I'm using is discribed here:
    Wikipedia - Image Moments
    I need to calculate this formula with different values for i and j:
    i.j = 0.0 - 0.1 - 1.0 - 1.1 - 0.2 - 2.0
    I programmed the code shown above/attached VI, but I need the optimize it for speed.
    The 2d array can be any size with a maximum of 2048 x 2048 with values varying between 0 and 4095.
    My question:
    How can I make this code faster?  
    Thank you and kudos will be given! 
    The Enrichment Center is required to remind you that you will be baked, and then there will be cake.
    Solved!
    Go to Solution.
    Attachments:
    Image Moment.vi ‏19 KB

    Hello falkpl,
    " If you are looking at moments, the IMAQ particle analysis will do moments on particles all in imaq to avoide the slower image to array.
    As for optomizing your code a few observations
    1. why are you using doubles- your image is 12 (actually 16bit in imaq)
    2. do nor calculate intedex on each itteration pre calculate these and cache.
    3. when possible do calculation on arrays at a time, ie multiple 2 arrays instead of doing it in a loop. "
    Thank you for your reply, sir.  As stated before, the "IMAQ Particle Analysis" only calculates moments on non-weighted (e.g. binary) particles.
    The formula above includes the weight of each pixel.
    1. The doubles are because the image is first filtered. This filter needs to convert the image to the DBL Type.
    2. Could you please elaborate this, sir? I do not understand what you mean.
    3. Effectively done in the solution. Thank you.
    The Enrichment Center is required to remind you that you will be baked, and then there will be cake.

  • LabVIEW 7.1 App (exe) hangs

    I am currently experiencing a problem where an application (exe) that was built using LabVIEW 7.1, hangs (or freezes).  No error dialog/s are displayed and  CPU usage is 100%.  The application must then be shutdown using the Windows Task Manager. This application is executing on a single core 1.6GHz Pentium M with 2GB RAM and running under Windows XP SP1.  A third party debugger that we are using indicates that the application does not exit the DLL "lvalarms.dll". 
    I've had a look at all of the postings on this forum and the known errors that relate to the "lvalarms.dll" DLL.  These all seem to indicate possible errors with this DLL only when using timed loops with multi-core PC's. 
    The version of "lvalarms.dll" that was shipped with 7.1 is 7.1.0.27.  Does anybody know if this is the latest version for 7.1.
    I am in possession of LabVIEW 8.5 but porting this app to 8.5 would mean quite a lot of development as we are using some of the DSC features.  Therefore this is not an option.
    Any ideas?
    Rob

    If an application seems to freeze and the CPU goes to 100%, it tends to be an issue with looping.  Either an infinite while loop or an extremely long unning for loop.  If the person who wrote the DLL code expected a loop to not run extremely long, they may have put no delay in the loop so it could fall out as fast as possible.
    So, do you have a siutation where you are calling a LV VI (probably a DSC VI) with bad parameters or an extremely large array?  I had an issue in the past where one of the algorithms happened to detect 0 (or really close to 0) instances, and I did a mth operation dividing a number by that result and using that as a loop counter, so I got a for loop running to an extremely high number, where typically, it only ran 100 times max.
    I also had a situation where the user put 0 in as a step size, and a while loop calculated the array of values.  Well, with a step size of 0, the while loop never terminated, since you got the same number out every time.

  • Amount of heap memory is occupied by  a Thread

    Hy, I am using threads in my application. I know the objects that are created inside the thread are stored in the heap space and this is for all the threads, right?
    So in the heap space are stored all the objects created for the threads.
    Is there a way to know the amount of heap memory is occupied by the objects created for a single thread ?
    I know I cant limit the stack memory for a thread but this memory is for the variables and not for the objects, right?
    Thanks

    Not really. The "size" of an object is a very complicated thing to compute, as it involves not only knowing the size of primitive objects and the size of references, but also a recursive calculation involving the size of objects referred to by the original object, taking into account that the object references form a directed graph and not necessarily a tree.
    That's probably more work than you want to do for whatever prompted this requirement, so I would suggest finding some simpler proxy calculation.

Maybe you are looking for