简体   繁体   中英

Finding the sum of a 5x5 array

I am having trouble with my code. I am trying to find the sum of this 5x5 array, but it keeps giving me a total of 0. When I use a 2x2 array it works, but it won't work for a 5x5. Can anyone please help?

import java.util.*;

public class QuestionOne
{
  public static void main(String[] args) 
  {
    Random rand = new Random();
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    int [][] numArray = new int [5][5];
    int average =0, totalRow=0;
    int highestVal=0, lowestVal=0;

    for (int row = 0; row < 5; row++)
    {
      num1 = rand.nextInt(1000) + 1;
      num4 =rand.nextInt(1000) + 1;
      for (int col = 0; col < 4; col++)
      {
        num2 = rand.nextInt(1000) + 1;
        num5 = rand.nextInt(1000) + 1;
      }
      num3 = rand.nextInt(1000) + 1;
      System.out.println(num1+" " +num2+" " +num3 +" " +num4 +" " +num5);
    }

    //Sum all values    
    int total;
    total =0;
    for (int row = 0; row < numArray.length; row++)
    {
      for (int col = 0; col < numArray[row].length; col++)
      {
        total = total + numArray[row][col];
      }
    }

    System.out.println("The total is " + total);
//System.out.println(numArray.length);

Here the issue is values are not setting to the array,

Please find below working code.

public static void main(String[] args) {
        Random rand = new Random();
        int num1=0, num2=0, num3=0, num4=0, num5=0;
        int [][] numArray = new int [5][5];
        int average =0, totalRow=0;
        int highestVal=0, lowestVal=0;

        for (int row = 0; row < 5; row++)
        {
          for (int col = 0; col < 5; col++)
          {
            num5 = rand.nextInt(1000) + 1;
            numArray[row][col] = num5;
          }
        }

        //Sum all values    
        int total;
        total =0;
        System.out.println(numArray.length);
        for (int row = 0; row < numArray.length; row++)
        {
          for (int col = 0; col < numArray[row].length; col++)
          {
            total = total + numArray[row][col];
            System.out.println("Row : " + row + "/Col : " + col);
            System.out.println("Total : " + total + "/value : " + numArray[row][col]);
          }
        }

        System.out.println("The total is " + total);

    }

Your random number generator isn't storing the values in the array, so your program isn't adding anything.

Personally, this is my more straightforward approach:

  1. Use a nested-for-loop and loop through array[i][j] = Math.random() function
  2. Create a (sum) variable and initialize to 0.
  3. Use another nested-for-loop and do: sum += array[i][j]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM