java help (2d arrays)

Discussion in 'Software' started by aimforthehead, Nov 1, 2011.

  1. aimforthehead

    aimforthehead Private E-2

    Hi guys. I am working on a program that takes in a 2d array, and uses two methods to return a 1d array. One method for the average value of each row. One for the columns. Here is what I have so far in trying to get the average of the rows (with little success...actually I am just trying to get the sum of the values in each row...don't know how to do that either.)

    public class TwoDaverage{
    public static void main(String[] args){
    double[] total;
    double[][] nums = {{2,5,7},{6,4,8},{1,3,9}};
    int i;
    for (i=0;i<nums.length;i++){
    total = rowAverage(nums);
    System.out.println(total);
    }

    }
    public static double[] rowAverage(double[][] row){
    double[] sum = new double[3];

    int i;
    int j;

    for (i =0; i < 3; i++){
    for (j = 0; j < 3; j++){

    sum[0] =sum + row[j];

    }
    }


    return sum;
    }
    }


    Any suggestions?
     
  2. PC-XT

    PC-XT Master Sergeant

    To help simplify the code, from the function, it looks like you meant the main loop to be
    Code:
    total = rowAverage(nums);
    for (i=0;i<nums.length;i++){
    System.out.println(total[i]);
    }
    with total assigned before the loop starts, so you can iterate through it.

    In the function,
    sum[0] =sum + row[j];
    should probably be
    Code:
    sum[i]+= row[i][j];
    assuming each sum starts at 0. I usually assign it, myself. I don't remember if Java zeros new variables automatically...
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds