Reputation: 47
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);
Upvotes: 0
Views: 492
Reputation: 28
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:
array[i][j] = Math.random()
functionsum += array[i][j]
Upvotes: 0
Reputation: 11
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);
}
Upvotes: 1