[英]Finding the sum of a 5x5 array
我的代码有问题。 我正在尝试查找此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);
这里的问题是值未设置为数组,
请在下面找到工作代码。
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);
}
您的随机数生成器未将值存储在数组中,因此您的程序未添加任何内容。
就个人而言,这是我更直接的方法:
array[i][j] = Math.random()
函数 sum += array[i][j]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.