[英]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.