找到5x5数组的总和

时间:2017-11-02 01:51:15

标签: java arrays

我的代码遇到问题。我试图找到这个5x5阵列的总和,但它总是给我总共0.当我使用2x2阵列时,它可以工作,但它不适用于5x5。有人可以帮忙吗?

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);

2 个答案:

答案 0 :(得分:1)

这里的问题是值没有设置到数组

请查看以下工作代码。

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);

    }

答案 1 :(得分:0)

您的随机数生成器不会将值存储在数组中,因此您的程序不会添加任何内容。

就个人而言,这是我更直截了当的方法:

  1. 使用嵌套for循环并循环执行array[i][j] = Math.random()函数
  2. 创建一个(sum)变量并初始化为0。
  3. 使用另一个嵌套for循环并执行:sum += array[i][j]