Sum of an array

Hey guys,
So I have an array with six values stored in them.
The values will either be 1 or 0.
I need to sum them up so that I get a number ranging from 0-6.
Any help on this rather noob question would be much appreciated!

just loop thru the array and add them up...
var arraySum:Number = 0;
for (var i:uint=0; i< yourArray.length; i++){
     arraySum += yourArray[i];

Similar Messages

  • Need help finding the sum of an array list

    I'm making a mock up of iTunes, I suppose, for class. My only issue is that I can't figure out how to add all the durations of each sound file when it's stated in the array.
    I've put the part I'm having trouble with in bold, it is located in the Jpod class. We're using a program called BlueJ for coding, which is why the commenting is slightly odd.
    import java.applet.*;
    import java.io.*;
    import java.net.*;
    public class SoundPlayer
        public SoundPlayer(String fileName, int duration)
            AudioClip testClip;
            URL testUrl;
            System.out.println("Playing " + fileName);
            try{
                testUrl=new URL("file:" + new File(".").getCanonicalPath() + "/" + fileName);
                testClip=Applet.newAudioClip(testUrl);
                testClip.play();
                Thread.sleep(duration*1000);
                testClip.stop();
            }catch(Exception e){ System.out.println(e.toString()); }
    public class Sound
        private String author;
        private String fileName;
        private int duration;
         * Constructor for objects of class Sound
        public Sound(String newAuthor, String newFileName, int newDuration)
            // initialise instance variables
            author = newAuthor;
            fileName = newFileName;
            duration = newDuration;
         * Returns the duration of the sound file
         * @return     duration of the sound file
        public int getDuration()
            // returns duration
            return duration;
         * Returns the author of the sound file
         * @return     author of the sound file
        public String getAuthor()
            //returns author
            return author;
         * Prints the author, filename, and duration
        public void printSound()
            System.out.println("Author: " + author + " File name: " + fileName + " Duration: " + duration);
         * Plays the sound
         * @return     sound file
        public void playSound()
            new SoundPlayer("Lab4.wav",3);
    import java.util.ArrayList;
    import java.util.Iterator;
    public class Jpod
        // instance variables - replace the example below with your own
        private ArrayList<Sound> playlists;
         * Constructor for objects of class Jpod
        public Jpod()
            playlists = new ArrayList<Sound>();
         * Adds a sound to the playlist
         * @param  sound   of type Sound
        public void addSound(Sound sound)
            // inserts the sound into the playlist
            playlists.add(sound);
         * Adds 3 sounds to a playlist
        public void createPlayList()
            Sound s;
            s = new Sound("Microsoft", "Lab4.wav", 2);
            addSound(s);
            s = new Sound("Dr. Evil", "DrEvil.wav", 4);
            addSound(s);
            s = new Sound("Arnold Schwarzenegger", "Terminator.wav", 2);
            addSound(s);
         * Remove desired sound object
         * @param indexNumber The number of the sound object to be removed
        public void removeSound(int indexNumber)
            if(indexNumber < 0){
                //Not a valid index number - do nothing
            else if(indexNumber < playlists.size()){
                //Valid indexNumber
                playlists.remove(indexNumber);
            else {
                //Not a valid index number - do nothing
         * Show the sound object
         * @param indexNumber The number of the sound object to be shown
        public void getSound(int indexNumber)
            if(indexNumber < 0){
                //Not a valid index number - do nothing
            else if(indexNumber < playlists.size()){
                //Valid indexNumber
                System.out.println(playlists.get(indexNumber));
            else {
                //Not a valid index number - do nothing
         * @return The number of sounds in the playlist
        public int getSize()
            return playlists.size();
         * List all sounds in the playlist
        public void indexPrintList()
            for(Sound playlist : playlists) {
                playlist.printSound();
         * Lists all sounds in the playlist using an iterator
        public void iteratorPrintList()
            Iterator<Sound> iter = playlists.iterator();
            while(iter.hasNext()) {
                ((Sound)iter.next()).printSound();
         * Gives the total duration of all sounds in the playlist
        *public void totalDuration()*
            *//currently prints all durations - still working on sum*
            *for(Sound playlist : playlists) {*
                *System.out.println(playlist.getDuration());*
         * Plays through all the sounds in the playlist
         * Extra Credit
        public void indexPlayList()
            for(Sound playlist : playlists) {
                playlist.playSound();
         * Plays through all sounds in the playlist using an iterator
         * Extra Credit
        public void iteratorPlayList()
            Iterator<Sound> iter = playlists.iterator();
            while(iter.hasNext()) {
                ((Sound)iter.next()).playSound();
    }

    not sure if I'm missing something here, but this could possibly be solved by initializing a variable to 0 before the for loop, and then adding each duration to this variable as you loop. This seems too trivial a solution though. Again, I may be missing something here.
    something simple like:
    public void calcSum()
        int i = 0;
        for(Fubar foo: fooList) {
            i += foo.getLength();
        System.out.println("Sum = " + i);
    }Edited by: petes1234 on Oct 23, 2007 9:09 AM

  • Perculiar results of finding max sum of an array

    hi.
    I am doing an assigment of the time complexity of finding maxsum of an array. However, the time that i got for N log N algorithm is faster than the time of a N algorithm. Is there any reason with that? The same code is run on another machine but do that have the funny result. I am using a Microsoft Windows XP Professional, Laptop @ 1.4GHz of processor, Intel� 855GM chipset, 512MB DDR
    Further to that, what is a time complexity formula? Do we follow a certain standard to getting the formula?

    And what does that have to do with the javadoc tool, which this forum is for?

  • Summing 2D Array by Columns

    Im trying to sum a 2D array by column
    Say I have 5 rows and 5 columns im trying to get the sum of all the values in the second column.
    What I have so far and have been hassling with for a while is:
    public static float sumCol(int[][] table, int rowsize, int colsize)
          int[] c = new int[colsize];
          float sum=0;
          for (int row=0; row < rowsize; row++)
            for (int col=0; col < colsize; col++)
                c[col] = table [row][col];
                sum = myMethods.sum(c);
          return sum;the sum method calculates the sum of an array
    If you can help me and just give me some pointers on how to get this, 2D arrays I think play tricks on your mind.

    I dont understand why this is giving an out of bounds
    when i call it
    public static float sumCol(int[][] table, int
    rowsize, int colsize)
    int[] c = new int[colsize];
    float sum=0;
    for (int row=0; row < rowsize; row++)
    c[row] = table [row][colsize];
    sum = myMethods.sum(c);
    return sum;
    Because number of columns is not the same as number of rows.
    I still don't understand why you are creating an array. You don't need one.
    Kaj

  • SUM or array of objects?

    Hi
    I have an object called monitorPlot_0 on which I want to add i/b objects called reportMonitor_i.
    for ( b = 0; b =< 2; b = b + 1) {
    i = 0;
        for ( h = 0.5; h <= 2; h = h + 0.5) {
           i = b*i + 1;
           a=0; 
        MonitorPlot monitorPlot_0 =
          simulation_0.getPlotManager().createMonitorPlot();
        monitorPlot_0.setPresentationName("Reports Plot Unit " + b +"  "+ h + "m");
        ReportMonitor reportMonitor_i =
          areaAverageReport_i.createMonitor();
    monitorPlot_b.getMonitors().addObjects(reportMonitor_i);
    //    monitorPlot_0.getMonitors().addObjects(reportMonitor_0, reportMonitor_1, reportMonitor_2, reportMonitor_3);
      }I have a problem with this line which is wrong, I don't know how to code it properly:
    monitorPlot_b.getMonitors().addObjects(reportMonitor_i);I want to add i/b objects called reportMonitor_i in each monitorPlot_b, in this example, that's would create the following monitorPlot at the end:
    monitorPlot_0.getMonitors().addObjects(reportMonitor_0, reportMonitor_1, reportMonitor_2, reportMonitor_3);
    monitorPlot_1.getMonitors().addObjects(reportMonitor_4, reportMonitor_5, reportMonitor_6, reportMonitor_7);
    monitorPlot_2.getMonitors().addObjects(reportMonitor_8, reportMonitor_9, reportMonitor_10, reportMonitor_11);
    How can I create a sum or an array or something that stores 4 reportMonitors and then put these 4 reportMonitors into the monitor plot?

    I'm still having a tough time figuring out what exactly it is that you want. Your code however seems array-deficient. Everywhere I see an underscore-number, I'm thinking that an array would go nicely there. I also am not a fan of your for loop that uses a floating point number (h) as its index, especially if it is relying on an == or equal variant (<= or >=) as its terminating condition since == is hard to come by with floating point numbers. I think much more reliable is to use an int for loop and then calculate your "h" or height when you need it. Something like,
          for (int apartment = 0; apartment < monitorPlots.length; apartment++) {
             int i = 0;
             monitorPlots[apartment] = simulations[apartment].getPlotManager()
                   .createMonitorPlot();
             for (int level = 0; level < 4; level++) {
                double height = 0.5 + level * 0.5;
                MonitorPlot monitorPlot = new MonitorPlot(apartment, height);
                monitorPlots[apartment].add(apartment, monitorPlot);
          }Also, please consider using variable names that make sense, that auto-comment the code for you.
    edit: also 2: consider looking into using ArrayLists. They're sort of like flexible arrays that can have changing number of items held in them.
    also 3: Please look over this link -- [How To Ask Questions The Smart Way|http://catb.org/~esr/faqs/smart-questions.html] -- it may seem smarmy of me to give you a link to this, but if you read it, you will see that it can help you to write questions here that people will be better able to answer, that folks will want to answer. I know that it's helped me. I try to re-read this link about once a month.
    As always, much luck.
    Edited by: Encephalopathic on Aug 13, 2009 8:33 PM

  • Data Array

    Can some please help with this. I need to pass an array to a
    wsdl function. The type is an array of single byte elements in
    chunks of 300 KB or less.
    I was able to read the data (From XML file) and converted it
    to a 1 dimension data array. How can I determine what the size of
    that dataarray? And also is it even possible to break that array
    out into 300 KB Chunks?
    Thanks,
    Jimmy

    Remember my first day of getting into programming class.
    So here is the code for you:
    public class DataArray extends Object {
    // return Sum of the array elements
      public static double getSum(double [] a) {
        double sum = 0;
        for ( int i=0; i<a.length; i++) {
          sum += a;
    return sum;
    // return Average of the array elements
    public static double getAverage(double [] a) {
    return getSum(a)/a.length;
    // return Minimum of the array elements
    public static double getMinimum(double [] a) {
    double min = a[0];
    for ( int i=1; i<a.length; i++) {
    if ( a[i] < min ) min = a[i];
    return min;

  • Help with an Array problem

    How do I get the variable checkNumber to read from the input and exit if the user enters a value less than 0? I initially created the array to accept 10 integer values and then average and sum them using JOptionPane. Now I would like the user to be able to exit the program if a negative value is entered in the input. Here's how it looks so far and I understand the if statement is where I am losing it.
    import java.text.NumberFormat;
    import java.text.DecimalFormat;
    import javax.swing.*;
    class originalArray
        public static void main(String args[])
            int checkNumber;
            int inputArray[] = new int[10];
            int arrayLength = inputArray.length;
            Boolean keepRunning = true;
                while (keepRunning)
                for(int i=0;i<arrayLength;i++)
                inputArray=Integer.parseInt(JOptionPane.showInputDialog("Enter integer for array location "+i+" :"));
    //checkNumber = inputArray;
    if (checkNumber <0)
    System.exit(0);
    else
    {int sum = 0;
                String loc = "";
                for(int i=0; i<arrayLength; i++)
                    sum+= inputArray[i];
    loc+= "Array location " + i + " is " + inputArray[i] + "\n";
    double avg;
    NumberFormat formatter = new DecimalFormat ("#0.000");
    avg =(double)sum/10;
    JOptionPane.showMessageDialog (null, loc + "The sum or the array is " + sum + "\n The average of the array is " + formatter.format(avg));

    import javax.swing.*;
    import java.text.*;
    class OriginalArray
        public static void main(String args[])
            int checkNumber=0;
            int inputArray[] = new int[10];
            int arrayLength = inputArray.length;
            Boolean keepRunning = true;
            int sum = 0;
            String loc = "";
             while (keepRunning)
               for(int i=0;i<arrayLength;i++)
                             inputArray=Integer.parseInt(JOptionPane.showInputDialog("Enter integer for array location "+i+" :"));
    checkNumber = inputArray[i];
    if (checkNumber <0)
    System.exit(0);
    else
    continue;
    for(int i=0; i<arrayLength; i++)
    sum+= inputArray[i];
    loc+= "Array location " + i + " is " + inputArray[i] + "\n";
    double avg;
    NumberFormat formatter = new DecimalFormat ("#0.000");
    avg =(double)sum/10;
    JOptionPane.showMessageDialog (null, loc + "The sum or the array is " + sum + "\n The average of the array is " + formatter.format(avg));
    keepRunning=false;
    bye                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • No class method output... HELP!!!

    hi to everyone...
    how can i output the classes in the main class???
    the output i get is zero and i cannot figure out why...
    here is my code:
    //============================================================
    import java.io.*;
    import javax.swing.*;
    class methodmin{
    public static void makemin (int[] minimum){
         int min;
         int[] array = new int[10];
    // initialize the current minimum
    min = array[0];
    // scan the array
    for ( int index=0; index < array.length; index++ )
    if ( array[ index ] < min )
    min = array[ index ] ;
    JOptionPane.showMessageDialog(null,"Minimum of the array is: " + min
    + "\n"
    ,"Single Dimension Array"
                                                      ,JOptionPane.INFORMATION_MESSAGE);
    class methodmax{
    public static void makemax (int[] maximum){
         int[] array = new int[10];
    int max;
    // initialize the current maximum
    max = array[0];
    // scan the array
    for ( int index=0; index < array.length; index++ )
    if ( array[ index ] > max ) // examine the current element
    max = array[ index ]; // if it is the largest so far, change max
    JOptionPane.showMessageDialog(null,"Maximum of the array is: " + max
    + "\n"
    ,"Single Dimension Array"
                                                      ,JOptionPane.INFORMATION_MESSAGE);
    class methodsum{
    public static void makesum (int[] sum){
         int[] array = new int[10];
    // declare and initialize the total
    int total = 0 ;
    // add each element of the array to the total
    for ( int index=0; index < array.length; index++ )
    total = total + array[ index ] ;
    JOptionPane.showMessageDialog(null,"Sum of the array is: " + total
    + "\n"
    ,"Single Dimension Array"
              ,JOptionPane.INFORMATION_MESSAGE);
    class methodave{
    public static void makeave (int[] ave){
         int[] array = new int[10];
    // declare and initialize the total
    int total = 0 ;
         int index=0;
    // add each element of the array to the total
    for ( index=0; index < array.length; index++ )
    total = total + array[ index ] ;
    if ( array.length <= 0 )
    JOptionPane.showMessageDialog(null,"Average of the array is: " + total/array[index]
    + "\n"
    ,"Single Dimension Array"
                   ,JOptionPane.INFORMATION_MESSAGE);
    else
    JOptionPane.showMessageDialog(null,"The array contains no elements "
         ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    class mainmenu{
    public static void main(String[] args) {
    int i=0;
    int rep=0;
         int numba;
         String temp="";
    int[] anArray;
    anArray = new int[10];
    methodmin fmin = new methodmin();
    methodmax fmax = new methodmax();
    methodsum fsum = new methodsum();
    methodave fave = new methodave();
    JOptionPane.showMessageDialog(null,"This is a program that will \n"
    + "display the Minimum, Maximum, \n"
    + "Sum and Average numbers in a \n"
    + "Single Dimension Array \n"
    + "Using Objects and Classes"
    ,"Single Dimension Array"
                        ,JOptionPane.INFORMATION_MESSAGE);
    do{
    for(i=0; i<=9; i++)
    anArray=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter ten numbers"
    ,"Single Dimension Array"
    ,JOptionPane.QUESTION_MESSAGE));
    numba = anArray[0];
    for(i=0; i<=9; i++)
    numba = anArray[i];
    temp=temp+"\n"+numba;
    JOptionPane.showMessageDialog(null,"The Numbers Entered Are: " + temp
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    fmin.makemin(anArray);
    fmax.makemax(anArray);
    fsum.makesum(anArray);
    fave.makeave(anArray);
    rep = JOptionPane.showConfirmDialog (null,"Input another number?"
    ,"Single Dimension Array"
    ,JOptionPane.YES_NO_OPTION);
    while(rep==0);

    ive taken all your advices and guess what, the code now works!!! thanks to all of you who helped, more power and god bless!!!
    my problem now is on how to output the average... this is a bit tricky for me because i think i have to output it as a double or with decimal numbers...
    any ideas???
    ===========================================================
    import java.io.*;
    import javax.swing.*;
    class methodmin{
    public static int makemin (int[] minimum){
    int min;
    // initialize the current minimum
    min = minimum[0];
    // scan the array
    for ( int index=0; index < minimum.length; index++ )
    if ( minimum[ index ] < min )
    min = minimum[ index ] ;
    JOptionPane.showMessageDialog(null,"Minimum of the array is: " + min
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    return min;
    class methodmax{
    public static int makemax (int[] maximum){
    int max;
    // initialize the current maximum
    max = maximum[0];
    // scan the array
    for ( int index=0; index < maximum.length; index++ )
    if ( maximum[ index ] > max ) // examine the current element
    max = maximum[ index ]; // if it is the largest so far, change max
    JOptionPane.showMessageDialog(null,"Maximum of the array is: " + max
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    return max;
    class methodsum{
    public static int makesum (int[] sum){
    // declare and initialize the total
    int total = 0 ;
    // add each element of the array to the total
    for ( int index=0; index < sum.length; index++ )
    total = total + sum[ index ] ;
    JOptionPane.showMessageDialog(null,"Sum of the array is: " + total
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    return total;
    class methodave{
    public static int makeave (int[] ave){
    // declare and initialize the total
    int total = 0 ;
    int index= 0;
    // add each element of the array to the total
    for ( index=0; index < ave.length ; index++ )
    total = total + ave[ index ] ;
    if ( ave.length <= 0 )
    JOptionPane.showMessageDialog(null,"Average of the array is: " + total/ave[index]
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE );
    else
    JOptionPane.showMessageDialog (null,"The array contains no elements "
    ,"Single Dimension Array"
    , JOptionPane.INFORMATION_MESSAGE);
    return ave[index];
    class mainmenu{
    public static void main(String[] args) {
        int i=0;
        int rep=0;
         int numba;
         String temp="";
        int[] anArray;
        anArray = new int[10];
        methodmin fmin = new methodmin();
        methodmax fmax = new methodmax();
        methodsum fsum = new methodsum();
        methodave fave = new methodave();
            JOptionPane.showMessageDialog(null,"This is a program that will \n"
                                               + "display the Minimum, Maximum, \n"
                                               + "Sum and Average numbers in a \n"
                                               + "Single Dimension Array \n"
                                               + "Using Objects and Classes"
                                               ,"Single Dimension Array"
                                                ,JOptionPane.INFORMATION_MESSAGE);
            do{
            for(i=0; i<=9; i++)
               anArray=Integer.parseInt(JOptionPane.showInputDialog (null,"Enter ten numbers"
    ,"Single Dimension Array"
    , JOptionPane.QUESTION_MESSAGE));
    numba = anArray[0];
    for(i=0; i<=9; i++)
    numba = anArray[i];
    temp=temp+"\n"+numba;
    JOptionPane.showMessageDialog(null,"The Numbers Entered Are: " + temp
    + "\n"
    ,"Single Dimension Array"
    ,JOptionPane.INFORMATION_MESSAGE);
    fmin.makemin(anArray);
    fmax.makemax (anArray);
    fsum.makesum(anArray);
    fave.makeave(anArray);
    rep = JOptionPane.showConfirmDialog (null,"Input another number?"
    ,"Single Dimension Array"
    ,JOptionPane.YES_NO_OPTION);
    while(rep==0);
    JOptionPane.showMessageDialog(null,"Reading Arrays"+"\n Programmed by: Carl Anthony P. Estepa"
    ,"Single Dimension Array"
    , JOptionPane.INFORMATION_MESSAGE);

  • Knowing function blockdiagram

    how can i khnow the blockdiagram for each function in labview like the function Add Array Element,

    tinamoli wrote:
    in my vi ihave an array of n_elements,,and i want to subtract each element by the first element,,
    in the function i could find add array elements,,which if i know its block diagram ,maybe i can mimicking it for subtraction,,
    Why don't we keep all this in one place? Thanks!
    (And no, "add array elements" has really nothing to do with what you need. It will just give a single number that is the sum of all array elements, while you need to operate element by element.)
    LabVIEW Champion . Do more with less code and in less time .

  • How do i draw a graph in a applet from ny data

    Hi, again sorry to keep coming back to you guys, but i have been trying hard to attempt things myself.I have read loads of books and can not find example to work from.I have managed with your "help" to finnish my calculations. Now i need to plot a graph with the data from my X array and Y array. I will then try my self to plot the linear least fit line if it kills me. I would like to print stars on the graph using the points in my arrays. But where do i start
    sorry if i am asking to much i will understand if you can't help as you have really good programers asking proper questions instead of a novice like me.i have tried but get errors
    LinearLeast1.java:111: illegal start of expression
    public void paint (Graphics gr)
    ^
    LinearLeast1.java:120: ';' expected
    ^
    LinearLeast1.java:3: cannot resolve symbol
    symbol : class Applet
    location: class LinearLeast1
    class LinearLeast1 extends Applet
    ^
    3 errors
    lindsey
    code:
    import java.io.*;
    class LinearLeast1 extends Applet
    { // start of new class
    //defines the sum method
              public static double SumA (double arr[])
              double SumA =0; //sum of array
              if (arr.length >=1)
                   for(int i=0; i< arr.length; i++)
                        SumA +=arr;
              else
                   SumA =0; // insuficient data
                   return SumA;
              // defines the sum of XY array method
              public static double sumXY (double arrX[],double arrY[])
                   double SumXY=0; // sum of arrays X*Y
                   if(arrX.length>=2)
                        for(int i=0; i< arrX.length;i++)
                             SumXY +=arrX[i]*arrY[i];
                   else
                        SumXY=0;//insufficient data
                   return SumXY;
              //defines the avarage method
              public static double AverageB (double arr[])
              double SumA =0; //sum of array
              double AverageB =0; // average of array
              if (arr.length >=1)
                   for(int i=0; i< arr.length; i++)
                        SumA +=arr[i];
                   AverageB = SumA / arr.length;
              else
                   AverageB =0; // insuficient data
                   return AverageB;
              //defines array to the power of 2 method
              public static double SumB (double arr[])
              double SumB = 0; // sum of squares of array
              double SumA =0; //sum of array
              double Square =0; // array to the power of 2
              if (arr.length >=2)
                   for(int i=0; i< arr.length; i++)
                        SumA +=arr[i];
                        SumB += arr[i] * arr[i];     
                   Square =Math.sqrt((arr.length* SumB - SumA*SumA) / (arr.length*(arr.length-1)));
              else
                   Square =0; // insuficient data
                   return SumB;
                   public static void main(String[]args)
         { //start of main method
                                       //values for array x
              double [] arrX ={-4.91,-3.84,-2.41,-2.62,-3.78,-0.52,-1.83,-2.01,0.28,1.08,
              -0.94,0.59,0.69,3.04,1.01,3.60,4.53,5.13,4.43,4.12};
              // values for array y
              double [] arrY ={-8.18,-7.49,-7.11,-6.15,-5.62,-3.30,-2.05,-2.83,-1.16,0.52,
              0.21,1.73,3.96,4.26,5.75,6.67,7.70,7.31,9.05,10.05};
         double SumXY = sumXY(arrX,arrY);
    double m = (SumXY-(SumA(arrX)*AverageB(arrY)))/ (SumB(arrX)-(SumA(arrX)*AverageB(arrX)));
    double B = LinearLeast1.AverageB(arrY)-m*LinearLeast1.AverageB(arrX);
    // System.out.println(" m = "+ m );
    // System.out.println(" array X * array Y = "+LinearLeast1.sumXY(arrX,arrY));
         // System.out.println(" sum ofarray x "+ LinearLeast1.SumA(arrX));
         // System.out.println(" sum ofarray y "+ LinearLeast1.SumA(arrY));
         // System.out.println(" avarage of array x " + LinearLeast1.AverageB(arrX));
         // System.out.println(" avarage of array y " + LinearLeast1.AverageB(arrY));
         // System.out.println(" power of 2 array x " + LinearLeast1.SumB(arrX));
         // System.out.println(" m= "+m);
         // System.out.println(" B= "+B);
    public void paint (Graphics gr)
         for(int i=1; i< arr.length; i++)
    g.drawLine((i-1)*arrXSCALING, arr[i-1]*YSCALING,
    i*XSCALING, arr[i]*YSCALING);
    }//end of paint method
    } //end of main method
    } // end of class

    Thanks for that, I thought I upset every one, only just stopped crying
    here is my ammended code again before I go to bed, hope it's right this time
    import java.io.*;
    class LinearLeast1 extends Applet
    { // start of new class
                 //defines the sum method
                   public static double SumA (double arr[])
                  double SumA =0;      //sum of array
                  if (arr.length >=1)
                         for(int K=0; K< arr.length; K++)
                              SumA +=arr[K];
                      else 
                           SumA =0; // insuficient data
                           return SumA;
                  // defines the sum of XY array method
                  public static double sumXY (double arrX[],double arrY[])
                       double SumXY=0; // sum of arrays X*Y
                        if(arrX.length>=2)
                              for(int K=0; K< arrX.length;K++)
                                   SumXY +=arrX[K]*arrY[K];
                        else
                               SumXY=0;//insufficient data
                          return SumXY;
                  //defines the avarage method
                   public static double AverageB (double arr[])
                  double SumA =0;      //sum of array
                  double AverageB =0;  // average of array
                  if (arr.length >=1)
                         for(int K=0; K< arr.length; K++)
                              SumA +=arr[K];
                         AverageB = SumA / arr.length;
                     else 
                           AverageB =0; // insuficient data
                           return AverageB;
                    //defines array to the power of 2 method
                   public static double SumB (double arr[])
                  double SumB = 0;     // sum of squares of array
                  double SumA =0;      //sum of array
                  double Square =0;  // array to the power of 2
                  if (arr.length >=2)
                         for(int K=0; K< arr.length; K++)
                              SumA +=arr[K];
                              SumB += arr[K] * arr[K];     
                         Square =Math.sqrt((arr.length* SumB - SumA*SumA) / (arr.length*(arr.length-1)));
                     else
                           Square =0; // insuficient data
                           return SumB;
                    public static void main(String[]args)
         { //start of main method
                                       //values for array x
              double [] arrX ={-4.91,-3.84,-2.41,-2.62,-3.78,-0.52,-1.83,-2.01,0.28,1.08,
                             -0.94,0.59,0.69,3.04,1.01,3.60,4.53,5.13,4.43,4.12};
                                 // values for array y
              double [] arrY ={-8.18,-7.49,-7.11,-6.15,-5.62,-3.30,-2.05,-2.83,-1.16,0.52,
                                0.21,1.73,3.96,4.26,5.75,6.67,7.70,7.31,9.05,10.05};
            double SumXY = sumXY(arrX,arrY);
           double m = (SumXY-(SumA(arrX)*AverageB(arrY)))/ (SumB(arrX)-(SumA(arrX)*AverageB(arrX)));
          double B = LinearLeast1.AverageB(arrY)-m*LinearLeast1.AverageB(arrX);
       public void paint (Graphics gr)
          for(int K=1; K< arr.length; K++)
        g.drawLine((K-1)*arrXSCALING, arr[K-1]*YSCALING,
        K*XSCALING, arr[K]*YSCALING);
          }//end of paint method
       } //end of main method
    } // end of classHope that is better, I will take your advise and not give up. Will try to have another go tomorrow as it is 2.30am now. So I will try and get some sleep. Thanks again for coming back to answer I needed that bit of encouragement. Don't know if that bit of code for drawing my applet is right or not.
    good night and thanks again
    Lindsey

  • Something is wrong with my subTotal script

    The script actually works fine until you skip a line in the the form. Then the amount from that line is appended to the end of the Subtotal. For example: If the Price.0 field is $100.00 and the Price.1 field is $100.00, the Subtotal field shows $200.00. So far so good. Now if Price.3 is skipped and $50.00 is entered in Price.4, the Subtotal field shows $20,050.00.
    Here's the script:
    var subTotal = this.getField("Price.0").value
    + this.getField("Price.1").value
    + this.getField("Price.2").value
    + this.getField("Price.3").value
    + this.getField("Price.4").value
    + this.getField("Price.5").value
    + this.getField("Price.6").value
    event.value = subTotal;

    The "+" operator is used for an arithmetic addition or string concatenation and JavaScript looks at the 2 values involved and assumes what operation is being asked for. It the values are 2 numbers addition is assumed, if 2 character strings then concatenation is assumed, and if one value is a number and the other a character string concatenation is assumed. You need to use the "Number()" constrictor to force the calculation to use an arithmetic addition.
    Your script can be simplified by using some document level function to sum an array of fields.
    // document level function
    function SumArray(aValues) {
    var sum = 0; // sum
    // loop through array of values
    for(i = 0; i < aValues.length; i++) {
    sum += Number(aValues[i]);
    } // add element i to sum
    return sum; // return sum
    } // end function
    function MakeAValues(sFieldName) {
    var oField = this.getField(sFieldName); // get field object
    var aFields = oField.getArray(); // convert field object to an array of fields
    var aValues = new Array(aFields.length); // array for the values of the fields
    for(j = 0; j < aFields.length; j++) {
    aValues[j] = aFields[j].value;
    } // end for loop
    return aValues; // pass back array of values
    // end of document level functions
    // custom calculation script to sum a hierarchical group of fields
    // use defined function to:
    // create an array of values
    // sum that array of values
    event.value = SumArray( MakeAValues("Price") );
    You could also use this undocumented funcition:
    AFSimple_Calculate("SUM", "Price");
    But it will hide the script.

  • Using quadrature encoders with PXI-6025

    Hi!,
    We are using an encoder for position data. The encoder gives A and B pulses which are phase shifted by 90 deg.
    Grating Pitch = 40 microns
    We make the connection to our PXI-6025 as such:
    Channel A pulse goes to PFI 8 (GPCTR_Source)
    Channel B pulse goes to DIO6 (GP_Up_Down)
    Ground goes to DGND
    We are able to increment/decrement the counter on our 6025 for every 40 micron movement
    However, we are unable to quad the input and increment/decrement for every 10 microns. How do we achieve this?
    We have an electronic circuit which converts the 40 micron A and B pulse from the encoder into 4 pulses spaced at 10 microns. But, using this single pulse mode does not allow for up/down counting.
    We are using LV-7.1
    , NI-DAQ 7.2 and Win2000 prof.
    Looking forward to some quick help.
    Thanks,
    Gurdas
    Gurdas Singh
    PhD. Candidate | Civil Engineering | NCSU.edu

    There's one tedious way that might work if you only need to post-process the data. However there are several possible problems.
    The idea is to perform buffered semi-period measurements with both the counters on the 6025. Once you've collected all the needed semi-period data, perform a cumulative sum of each array so you end up with timestamps for all the transitions. Then you'll need to go through them to distinguish (+) from (-) direction quadrature transitions and generate a cumulative position array.
    I don't think there's another way -- only semiperiod measurements will react to both edges of an incoming pulse train. However, it *is* possible in principle to get your 4x factor in resolution. Now for the problem list:
    1. Your 6025E only has 1 DMA channel. One of the counters will have to be configured to use interrupts, which in turn will limit the maximum encoder rate you can track. I wouldn't count on tracking better than single digits of kHz, and you may not even be able to achieve that much.
    2. The last time I did semiperiods on an E-series board, there was no way to specify which edge would mark the first recognized transition. If the input was low when you started, the first transition recorded would be a rising edge; if high, then a falling edge.
    Knowledge of the initial state of the inputs is critical for your software quadrature decoding. I think the solution I used was to parallel wire the A&B channels to a couple DIO pins which I inspected before any encoder motion started. If your encoder jitters or vibrates about its nominal position however, you're probably hosed.
    Are you sure you can't use the LS7084 to replace your other external circuit? The alternatives are either going to be trouble-prone gimmicks like I described above or the purchase of new DAQ equipment.
    If you have budget for new DAQ equipment from NI, I'd suggest you look into one of the following:
    1. Low-cost M series multi-function board
    These have 2 32-bit counters onboard that are capable of quadrature decode. Each counter gets its own DMA channel for buffered acquisition. Plus you get a bunch of analog in, timed digital i/o, and can get analog outs. The boards are $475 with 2 analog outputs, $375 with none.
    2. dedicated counter/timer board
    The 6601 is cheaper at $295, but is limited to 1 DMA channel and has a slower onboard timing clock. The 6602 costs about double that but gives you somewhat more than double capability.
    -Kevin P.

  • .class error

    Hi,
    I am trying to make a simple code where a main program calls a method in a class so that the total sum of all elements of an array is calculated. Here is my code:
    public class playingwithArrays
            static void sumArray(int [] arr){
                int sum = 0;
                    for(int i = 0; i<arr.length; i++){
                        sum+= arr;
    System.out.println ("Total sum of array is" + sum);
    This is the class where there is the method i want to access
    The class below is the main class:public class Start
    public static void main (STring[] args){
    int [] arr = new int [10];
    for (int i; i<arr.length; i++){
    arr[i] = (i+1);
    playingwithArrays summation = new playingwithArrays ();
    summation.sumArray(int arr[]);
    Where there is bold the compiler is giving me a .class error. Please can you help me as I am a beginner and I am trying to learn java!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    It's a good idea to follow standard conventions about nAmEs. PlayingWithArrays, not playingwithArrays.
    You define sumArray() as a static method. That means that it will not be associated with a particular instance of the PlayingWithArrays class. And so you can access it without having to create a new instance of the class.
    It's not actually wrong to say summation.sumArray(...), it's just that it looks odd. It would better be PlayingWithArrays.sumArray(...).
    The actual error is what you are passing as the argument. This method expects an array of int and that's what you should pass it. You don't need the int and [] business that goes into the declaration of a method, just use the variable.
    PlayingWithArrays.sumArray(arr);This will use a static method of the PlayingWithArrays class to print out the sum of the array elements.

  • Problems with a while loop within a method... (please help so I can sleep)

    Crud, I keep getting the wrong outputs for the reverseArray. I keep getting "9 7 5 7 9" instead of "9 7 5 3 1". Can you guys figure it out? T.I.A (been trying to figure this prog out for quite some time now)
    * AWT Sample application
    * @author Weili Guan
    * @version 1999999999.2541a 04/02/26
    public class ArrayMethods{
       private static int counter, counter2, ndx, checker, sum, a, size, zero;
       private static int length;
       private static int [] output2, output3, reverse, array;
       private static double output;
       private static double dblsum, dblchecker, average;
       public static void main(String[] args) {
          //int
          //int [] reverse;
          System.out.println("Testing with array with the values [1,3,5,7,9]");
          size = 5;
          array = new int [size];
          reverse = new int [size];
          array[0] = 1;
          array[1] = 3;
          array[2] = 5;
          array[3] = 7;
          array[4] = 9;
          System.out.println("Testing with sumArray...");
          output = sumArray(array);
          System.out.println("Sum of the array: " + sum);
          System.out.println();
          System.out.println("Testing with countArray...");
          output = countArray(array);
          System.out.println("Sum of the elements : " + checker);
          System.out.println();
          System.out.println("Testing with averageArray...");
          output = averageArray(array);
          System.out.println("The average of the array : " + average);
          System.out.println();
          System.out.println("Testing with reverseArray...");
          output2 = reverseArray(array);
          output3 = reverseArray(reverse);
          //System.out.print(reverse[4]);
          System.out.print("The reverse of the array : ");
          for(ndx = 0; ndx < array.length; ndx++){
             System.out.print(reverse[ndx] + " ");
       private ArrayMethods(){
       public static int sumArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if (array[ndx] > 0){
                checker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                sum += array[ndx];
                ndx++;
             return sum;
          else{
             sum = 0;
             return sum;
        /*Computes the sum of the elements of an int array. A null input, or a
        zero-length array are summed to zero.
        Parameters:
            array - an array of ints to be summed.
        Returns:
            The sum of the elements.*/
       public static int countArray(int[] array){
          checker = 0;
          ndx = 0;
          counter = 0;
          sum = 0;
          while(counter < array.length){
             if(array[ndx] > 0 && array[ndx] != 0){
                checker++;
             counter++;
          return checker;
        /*Computes the count of elements in an int array. The count of a
        null reference is taken to be zero.
        Parameters:
            array - an array of ints to be counted.
        Returns:
            The count of the elements.*/
       public static double averageArray(int[] array){
          dblchecker = 0;
          ndx = 0;
          counter = 0;
          dblsum = 0;
          while(counter < array.length){
             if(array[ndx] > 0){
                dblchecker++;
             counter++;
          if(array.length > 0 && checker == array.length){
             while(ndx < array.length){
                dblsum += array[ndx];
                ndx++;
             average = dblsum / dblchecker;
             return (int) average;
          else{
             average = 0;
             return average;
        /*Computes the average of the elements of an int array. A null input,
        or a zero-length array are averaged to zero.
        Parameters:
            array - an array of ints to be averaged.
        Returns:
            The average of the elements.*/
       public static int[] reverseArray(int[] array){
          ndx = 0;
          counter = 0;
          counter2 = 0;
          if(array.length == 0){
             array[0] = 0;
             return array;
          else{
                //reverse = array;
             while(ndx <= size - 1){
                   reverse[ndx] = array[4 - counter];
                   counter++;
                   ndx++;
                   System.out.print("H ");
          return reverse;
        /*Returns a new array with the same elements as the input array, but
        in reversed order. In the event the input is a null reference, a
        null reference is returned. In the event the input is a zero-length array,
        the same reference is returned, rather than a new one.
        Parameters:
            array - an array of ints to be reversed.
        Returns:
            A reference to the new array.*/
    }

    What was the original question? I thought it was
    getting the desired output, " 9 7 5 3 1."
    He didn't ask for improving the while loop or the
    reverseArray method, did he?
    By removing "output3 = reverseArray(reverse):," you
    get the desired output.Okay, cranky-pants. Your solution provides the OP with the desired output. However, it only addresses the symptom rather than the underlying problem. If you'd bother yourself to look at the overall design, you might see that hard-coding magic numbers and returning static arrays as the result of reversing an array passed as an argument probably isn't such a great idea. That's why I attempted to help by providing a complete, working example of a method that "reverses" an int[].
    Removing everything and providing "System.out.println("9 7 5 3 1");" gets him the desired output as well, but (like your solution) does nothing to address the logic problems inherent in the method itself and the class as a whole.

  • Calculating beat per minute

    Hello,
    I wrote a multichannel data acquisition code including Respiration ,ECG and GSR (Galvanic Skin Response). I want to calculate beat per minute and breathing rate. I�ve used a threshold peak detector. I�ve thought that the difference of the index of the first peak and th index of the second peak generates the number of total samples between two consecutive counts. To count the beat rate per second I divided sample rate by the number of samples per beat. Then I�ve multiplied beat rate per second by 60 to generate beat rate per minute. I also did the same thing for breath rate per minute.
    The problem is the result wasn�t successful. As you can see in the attachment I�ve calculated bpm as 253 and brpm is 538. BPM should be
    60 for a healthy person and BRPM should be 15.
    Ther is nothing wrong with my signals. But as you can see in the diagram data comes as #4 and difference between index of the first peak and the index of the second peak is quite high.
    What do you recommend me to do to calculate the correct values.
    Thanks
    Attachments:
    multichannel.JPG ‏89 KB
    diagram.JPG ‏100 KB

    Have a look on the attached vi.
    The first loop runs in 1 second, generating an array of 100 random numbers;
    The second loop calculates the sum of the array elements, and would run every 0.2 seconds.
    Except that the occurence nodes synchronize the calculation with the availability of the data array.
    You can experiment the effect of occurence by removing the nodes : the vi still runs, but the led blinks 5 times more rapidly.
    Last comment : don't forget the ultimate set occurence when exciting the first loop, otherwise the second loop will wait for ever...
    Ask if you need more help.
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Synchro_loops.vi.zip ‏13 KB

Maybe you are looking for