Java: 2d array totals not completing - java

This is a school project. It is to display the info from the array into a tubular format with totals on the right side and across the bottom for each row and column. It does all the totals except one row. I can't find where the problem is. Can anyone help?!
import java.util.Scanner;
//program uses class Scanner
public class Ex6_20
{
//method begins java application
public static void main(String[] args)
{
//create Scanner to obtain imput
Scanner input = new Scanner(System.in);
int monthySales=0; //varible to hold mothly sales
int productNum; //varible to hold product number
int salesNum=0; //varible to hold saleperson number
int totalSales=0; //varible to hold total sales
int []totalProduct = {0,0,0,0,0};//build array to hold total product
int []salesTotal = {0,0,0,0,0};//build array to hold total salesperson
// Build array to hold sales information by salesperson and poduct
int[][]sales = {{2000,1500,500,800,0},
{500,2200,600,1000,0},
{1000,2000,300,2100,0},
{2500,4000,400,3000,0},
{300,3200,500,2300,0},
{0,0,0,0}};
//figure total by product
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
totalProduct[column] += sales[row][column];
}//end for
//figure total by salesperson
for(int column = 0; column < sales.length; column++)
{
for(int row = 0; row < sales[column].length; row++)
salesTotal[row] += sales[column][row];
}//end for
//fill totals for product
for(int i = 0; i < 5; i++)
{
sales[i][4] = totalProduct[i];
}//end for
//fill totals for salesperson
for(int i = 0; i < 4; i++)
{
sales[5][i] = salesTotal[i];
}//end for
// print info from array in table format
for(int row =0; row < sales.length; row++)
{
for(int column = 0; column < sales[row].length; column++)
System.out.print(sales[row][column]+"\t");
System.out.println();
}//end for
} //end main method
} //end class

There are a few problems:
If you swap the variable names "row" and "column" in "figure total by salesperson" you'll notice that you are actually doing exactly the same calculation as "figure total by product", just with misleading variable names. (You're using column as the row index, and vice versa.) As of now, both totalProduct and salesTotal contain identical values, which is not right.
That is the main problem.
Also, when you display sales total and product totals, they are actually swapped. I suspect this is because you mean to have a total product per row with totalProduct[row] += ... and a total sales per column with salesTotal[column] += ..., but maybe the names are just swapped and the row/column indices are ok.
I'd actually recommend removing the extra sum fields from the sales array so all of the rows have the same number of columns and using hard-coded array bounds to start with, in order to make it more obvious what's happening until you get the sums correct. Then once the sums come up right, you can go back and make it work more generally. Otherwise, you may keep getting ArrayIndexOutOfBounds exceptions without it being obvious why, which is how I suspect you ended up with this solution so far.
For example, you could start with something very straightforward like this, then go back and make it a lot nicer and more general so it can work with different array sizes:
int[][] table = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } };
int[] rowSums = new int[3];
int[] colSums = new int[5];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
rowSums[i] += table[i][j];
colSums[j] += table[i][j];
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(table[i][j]);
System.out.print('\t');
}
System.out.println(rowSums[i]);
}
for (int j = 0; j < 5; j++) {
System.out.print(colSums[j]);
System.out.print('\t');
}
System.out.println();

Related

How to fix the following error java.lang.ArrayIndexOutOfBoundsException

I wanted to ask a question of code that has grated ja, I have the following code, I am going through a 10x5 array to fill it with number 1, to 49 for a primitive and the function that is responsible for making ticket gives me very rare errors. Index On Bound in theory the function would not have to go out of the way but I do not know what to do if someone can hit me.
// It is this part that gives me an error, I have a fly
int ,c=0;
int m[][]= new int[10][5];
for (int i=0;i<m.length;i++) {
for (int x=0;x<m.length;x++,i++) {
m[x][i]=c;
}
}
// This part of code I only have to check if the data output
// does them correctly
for(int i=0;i<m[0].length;i++) {
for(int x=0;x<m.length;x++) {
System.out.print(" "+m[i][x]+" ");
}
System.out.println(" ");
}
}
El error que me da es siguiente:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at provas/provas.main.main(main.java:11)
Looks like you want to fill given array with numbers from 1 to 49. So you have to pay attention on:
int[][] arr = new int[10][5] creates an int array with 10 rows and 5 columns
arr.length gives you a total rows amount
arr[0].length given you a total columns amount at row 0 (each row could have different length).
public static int[][] fillArray(int[][] arr) {
int i = 1;
for (int row = 0; row < arr.length; row++)
for (int col = 0; col < arr[row].length; col++)
arr[row][col] = i++;
return arr;
}
And finally to print an array:
public static void printArray(int[][] arr) {
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[row].length; col++)
System.out.format("%3d", arr[row][col]);
System.out.println();
}
}
You original method could be like this:
int[][] arr = fillArray(new int[10][5]);
printArray(arr);

Adding columns in an array that is created using command line arguments

My goal for this program is to create a 2D-array ratings whose size is specified by the first two arguments from the command line. args[0] would represent the number of rows r and arg[1] would represent the number of columns c. The next arguments that follow would all be used to fill in the array. So if the command-line argument was 3 2 5 2 3 3 4 1. I would hope that the array would be 3 rows by 2 columns. The value 5 would be in ratings[0][0], the value 2 would be in ratings[0][1], the value 3 would be in ratings[1][0], etc. After that, I want to compute the sum of each column. So column 0 would be 12 and column 1 would be 6 in this scenario.
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
int c = Integer.parseInt(args[1]);
int[][] ratings = new int[r][c];
int z = 2;
int y = 3;
int x = 0;
int counting = 0;
int sum = 0;
for (int rows = 0; rows < ratings.length; rows++ ) {
for (int column = 0; column < ratings[c].length; column++){
ratings[rows][column] = Integer.parseInt(args[z]);
sum += ratings[rows][column];
z++;
}
System.out.println(sum);
sum = 0;
}
//System.out.println(movieRating);
}
This is my attempt at summing the columns but this right now just sums 5 and 2, 3 and 3, 4 and 1. I want the columns not the rows to be summed but do not know how to fix it. Thank you
You seem to be adding the values to the 2D array correctly. What you're missing is an additional nested loop to print out the column totals:
for (int i = 0; i < ratings[c].length; i++) {
int colSum = 0;
for (int j = 0; j < ratings.length; j++) {
colSum += ratings[j][i];
}
System.out.println(colSum);
}
Add that where you currently have that //System.out.println(movieRating); line. Since you were adding the numbers to the array row-wise, you need to flip the for loops to be able to sum the columns.
Things you did right
You correctly initialized the ratings 2D-array with the values given on the command line. Let me re-write this below without your attempt at computing the columns' sum. Note that I renamed the variables so that the indices used in the for loop are single letter variable.
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
argIndex++;
}
}
}
Thing you didn't get right
The ratings array is filled row by row. In the code you posted, you compute in variable sum the sum of the elements inserted in the same row. This is the reason why it doesn't print the results you expected.
To compute the sum of each columns, I would recommend you create a new array in which to store this result. Integrating it with the code above:
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int[] columnSums = new int[columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
columnSums[c] += ratings[r][c];
argIndex++;
}
}
// array columnSums contains your results
}
I have changed your original code with a simpler version.
Let me know if you have problems understanding the solution.
public static void main(String[] args)
{
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int arrayLength = row * col; // use a single dimension array, for simplicity
int[] ratings = new int[arrayLength]; // the array size is based on the rows and columns
// add data to the 'ratings' array
// This is not actually needed because the conversion can be done directly when the columns are summed up
for(int i = 0; i < arrayLength; i++)
{
ratings[i] = Integer.parseInt(args[i + 2]);
}
// sum up the columns using the % operator
int[] result = new int[col];
for(int i = 0; i < arrayLength; i++)
{
result[i % col] += ratings[i];
}
// print result
for(int i = 0; i < result.length; i++)
{
System.out.println(String.format("Movie %d rating is %d", i, result[i]));
}
}
PS: you are missing the validation around the String to int conversion and checks around the correctness of the user input

How to print first five elements of an matrix in Java

My goal is to implement the following method in parallel:
public static double[][] parallelAddMatrix(double[][] a, double[][] b), then test my program on randomly generated two lists of size 2000 x 2000. Finally I have to output the first 5 elements of matrix a and matrix b, and also the first five elements of the result matrix, which is what I'm having trouble with.
This is the part of my code where I create the first and second matrix.
public static void main(String[] args) {
int var1, var2;
final int matrices = 2000;
// creates first matrix
double[][] matrixA = new double[matrices][matrices];
for(var1 = 0; var1 < matrixA.length; var1++)
for (var2 = 0; var2 < matrixA[var1].length; var2++)
matrixA[var1][var2] = 1;
// creates second matrix
double[][] matrixB = new double[matrices][matrices];
for (var1 = 0; var1 < matrixB.length; var1++)
for (var2 = 0; var2 < matrixB[var1].length; var2++)
matrixB[var1][var2] = 1;
And then later created a function to create the result matrix...
public static double[][] parallelAddMatrix( double [][] a, double[][] b) {
//creates output matrix
double[][] resultMatrix = new double[a.length][a[0].length];
RecursiveAction task = new multiProcess(a, b, resultMatrix);
ForkJoinPool joinPool = new ForkJoinPool();
joinPool.invoke(task);
return resultMatrix;
}
How can I print out the first five elements for each of the three matrices?
I've tried stuff for the first and second matrix such as initializing var3, then under the "matrixA(orB)[var1][var2] = 1;", I put
for (var3 = 0; var3 < 5; var3++) {
System.out.println(var3);
}
and also tried
for (var3 = 0; var3 < 5; var3++) {
System.out.print(matrixA[var1][var2] + "");
}
System.out.println();
Please help on this, and please tell where it would be placed for each one (I might have trouble with brackets).
You'll need a nested for loop to iterate through the matrix, and a counter to see how many entries you've printed. Let's start with the easiest part: iterating over the matrix. I'll assume that the matrix is simply called matrix.
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
}
}
You probably already figured that out. Now we need a counter to count how many times we've printed out an entry from the matrix.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]);
num_printed ++;
}
}
Ok. So now we need to stop once we've reached the end. We can't just use one break statement, because, we have two for loops.
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
break;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
if (num_printed == 5) { // so that we don't go to the next row
break;
}
}
It's worth noting that you could create your own separate method, and only use a return statement:
public void print_five_elements() {
int num_printed = 0;
for (int i = 0; i < matrix.length; i++) { // iterate over the rows
for (int j = 0; j < matrix[i].length; j++) { // iterate over the columns
if (num_printed == 5) { // if we've already printed five items, stop
return;
} else { // otherwise, print the next item
System.out.println(matrix[i][j]);
num_printed ++; // increment the counter
}
}
}
}
More Specialized Approach
This approach allows you to use matrices that have less than five columns. However, since your matrix is 2000x2000, you could go for a much simpler approach. Use zero as the first index, and then just iterate up to five. Just keep in mind that this won't work if you have less than five columns:
public void print_five_elements_for_wide_matrix() {
for (int i = 0; i < 5; i++) {
System.out.println(matrix[0][i]);
}
}
Since the matrices are of size 2000 x 2000, you do not need nested loops to display first 5 elements from each of them.
int i;
//Display first 5 elements of matrixA
for(i=0; i<5; i++) {
System.out.print(matrixA[0][i] + " ");
}
System.out.println();
//Display first 5 elements of matrixB
for(i=0; i<5; i++) {
System.out.print(matrixB[0][i] + " ");
}
System.out.println();
double[][] result = parallelAddMatrix(matrixA, matrixB);
//Display first 5 elements of result
for(i=0; i<5; i++) {
System.out.print(result[0][i] + " ");
}
System.out.println();
Note that the above loops print the first 5 elements of the first row (i.e. row at index, 0) of each matrix. However, if you want to print the first element of the first 5 rows, just swap the indices e.g.
System.out.println(matrixA[i][0] + " ");
Try this:
Think of the first set of brackets as the row and the second set as the column.
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
System.out.print(matrixA[row][col] + " ");
}
System.out.println();
}
Since "multi-dimensional" arrays are really arrays of arrays you can do it like this if you wanted to print out the whole matrix
for (double[] row : matrixA) {
System.out.println(Arrays.toString(row));
}
Because of this, each row can be a different length. So you may have to get the length to print them out like you first wanted to.
for (int row = 0; row < matrixA.length; row++) {
for (int col = 0; col < matrixA[row].length; col++) {
System.out.print(matrixA[row][col] + " " );
}
}
Rows of different length of a "2D" array are known as ragged-arrays.

Transpose java error

I was trying to do a 2D array program to demonstrate a TRANSPOSE but I am getting error .. here is my code.
import java.util.Scanner;
/* To demonstrate TRANSPOSE USING 2-D array */
public class Array_2ddd {
public static void main(String args[]) {
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[9][9];
int myArray2[][] = new int[9][9];
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.println("Enter array from 1 to 9");
myArray1[i][j] = s1.nextInt();
System.out.print("your array is" + myArray2[i][j]);
}
}
// Transposing now...
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
System.out.print("Your array is as follow" + myArray2[i][j]);
}
}
}
}
EDIT: My error during runtime (Solved)
EDIT 2: Solved
EDIT 3: The loop is in infinity ..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity..
There are several errors in your code, also it is recommend that the dimensions of the array is to be declared as a final int, so your code works for all matrix sizes and that debugging is easier. In your original code, the errors are:
At the input step, you are printing one element of myArray[2] before you perform the transpose. That means, you are getting your array is0.
In the section commented "After transposing", you are outputting your array wrong. Namely, for each entry, you call System.out.print("Your array is as follow" + myArray2[i][j]);, and that you forgot to add a new line after each row (when inner loop is finished).
"..it keeps on asking for values fromt the user even when i wrote i<9 and j<9..it still keeps on asking for values till infinity.." There are 81 entries for the 9-by-9 case and you did not output which i,j index to be applied. You probably mistaken an infinite loop with a long but terminating loop.
Your transpose step is good.
Here is a refined version of your code which allows you to input array (in reading order, or more technically, row-major order), create a transposed array. You can copy and compare your current code with this code directly to test it.
public static void main(String args[]) {
final int m = 9; // Rows
final int n = 9; // Columns
Scanner s1 = new Scanner(System.in);
int i, j;
int myArray1[][] = new int[m][n]; // Original array, m rows n cols
int myArray2[][] = new int[n][m]; // Transposed array, n rows m cols
// Input
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
// Should be only prompt.
// Improved to show which entry will be affected.
System.out.printf("[%d][%d]" + "Enter array from 1 to 9\n", i, j);
myArray1[i][j] = s1.nextInt();
}
}
// Transposing now (watch for the ordering of m, n in loops)...
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
{
myArray2[i][j] = myArray1[j][i];
}
}
// After transposing, output
System.out.print("Your array is:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
System.out.print(myArray1[i][j] + " ");
}
System.out.println(); // New line after row is finished
}
System.out.print("Your transposed array is:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(myArray2[i][j] + " ");
}
System.out.println();
}
s1.close();
}
For an array with three rows (m = 3) and four columns (n = 4), I inputted the numbers from 0 to 9, and then 0, 1, 2. As expected, the output should be:
Your array is:
0 1 2 3
4 5 6 7
8 9 0 1
Your transposed array is:
0 4 8
1 5 9
2 6 0
3 7 1
You define your matrix as 9x9
int myArray1[][] = new int[9][9];
But actually you want to insert 10x10 items:
for (i = 0; i <= 9; i++)
{
for (j = 0; j <= 9; j++)
So either:
Redefine your arrays to store 10x10 items
int myArray1[][] = new int[10][10];
Only read and store 9x9 items in your defined array
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++)
You haven't close your first outer for loop i.e in line 17 and change your array size to 10,as you wanted take 10 input (for 0 to 9 = 10 values).

2D Array in Java with number manipulation

My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}

Categories