Java Matrices Dot Product ArrayIndexOutOfBoundsException - java

I'm getting an error on line 66 c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];. I went through the indices by hand, just can't figure out where the index went wrong. Help is greatly appreciated.
package arrayproducts;
import javax.swing.JOptionPane;
public class ArrayProducts {
public static void main(String[] args) {
String output = "";
int rowA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixA."));
int colA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixA."));
int rowB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixB."));
int colB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixB."));
if( colA != rowB){
output += "Cannot perform matrix operation: Inner matrix dimensions must agree.";
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
output += "\nMatrixB has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
return;
} else {
output += "\nDot Product Begin:";
int [][] a = new int[rowA][colA];
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
int [][] b = new int[rowB][colB];
output += "\nMatrixA has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
int [][] c = new int[rowA][colB];
////
// enter first matrix
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colA; j++){
a[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixA, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add first matrix to output
output += "\nThe first matrix is: \n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colA; j++){
output += " " + a[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// enter second matrix
for(int i = 0; i < rowB; i++){
for(int j = 0; j < colB; j++){
b[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixB, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add second matrix to output
output += "\nThe second matrix is: \n";
for(int i=0; i < rowB; i++){
for(int j=0; j < colB; j++){
output += " " + b[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// compute the product
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colB; j++){
for(int k = 0; k < colA ; k++){ // either colA or rowB will work here
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];
}
}
}
output += "\nThe product of MatrixA and MatriB is:\n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colB; j++){
output += " " + c[rowA][colB];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
}

I guess you meant to use the indices i,j,k instead of rowA, colB etc in the following code.
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];

I will show you a simple example.
int[] a = new int[3];
That mean a can have only 3 values.
a[0], a[1] and a[2]
If you try a[3] it will be out of bound.
So. You have
int [][] c = new int[rowA][colB];
And try to access c[rowA][colB] which is out of bound.
In your three for loops, I think, you want to use i,j and k.

Related

Array sum rows and colums of an array

import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
int n, m, sumRows= 0, sumColumns= 0, i = 0, j = 0; //rows(n), Columns(m)
n = Integer.parseInt(JOptionPane.showInputDialog(null, "Rows"));
m = Integer.parseInt(JOptionPane.showInputDialog(null, "Columns"));
int[][] a = new int[n][m];
int[] b = new int[n];
int[] c = new int[m];
for(i = 0; i < a.length; i++) {
for(j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null, "Type"
+ "an int. A[" + i +"]" + "[" + j + "] = "));
sumRows+= a[i][j];
sumColumns+= a[j][i];
if(j == a[i].length-1) {
b[i] = sumRows;
sumRows= 0;
}
if(i == a.length-1) {
c[j] = sumRows;
sumRows= 0;
}
System.out.println("Sum Rows: " + sumRows+ " Vector B" + i + ": " + b[i]);
System.out.println("Sum Columns: " + sumColumns + " Vector C" + j + ": " + c[j]);
}
}
}
}
So i have to sum the rows and colums and store them on two vectors, i have to store the sum of the rows in Vector B, and the sum of the columns in Vector C.
The sum of the rows works perfectly, but i can't get to work the sum of the columns.
Try this:
public class Main {
public static void main(String[] args) {
int n = Integer.parseInt(JOptionPane.showInputDialog(null, "Rows"));
int m = Integer.parseInt(JOptionPane.showInputDialog(null, "Columns"));
int[][] a = new int[n][m];
int[] b = new int[n];
int[] c = new int[m];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = Integer.parseInt( JOptionPane.showInputDialog(null, "Type" + "an int. A[" + i + "]" + "[" + j + "] = "));
b[i] += a[i][j];
c[j] += a[i][j];
}
}
// USED FOR PRINTING
// -------------------------
for (int i = 0; i < b.length; i++) {
System.out.println("Sum Row " + (i + 1) + " is " + b[i]);
}
for (int i = 0; i < c.length; i++) {
System.out.println("Sum Column " + (i + 1) + " is " + c[i]);
}
// -------------------------
}
}
INPUT:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
OUTPUT:
Sum Row 1 is 10
Sum Row 2 is 35
Sum Row 3 is 60
Sum Row 4 is 85
Sum Column 1 is 30
Sum Column 2 is 34
Sum Column 3 is 38
Sum Column 4 is 42
Sum Column 5 is 46

Generate Random Number - Put into List - Print List

I have a program that generates a list of numbers and computes all into a total and separates them into three different list. One being all of the numbers, and the other two are even and odd and then prints the even and odd array-list.
or some reason when I try to print out the two list, it only prints the first couple of numbers in the ArrayList giving my no error messages.
My Code:
import java.util.Random;
import java.util.ArrayList;
public class Projects {
public static void main(String [] args) {
Random Generate = new Random ();
ArrayList<Double> List = new ArrayList<>();
ArrayList<Double> Even = new ArrayList<>();
ArrayList<Double> Odd = new ArrayList<>();
double number;
double total = 0;
double totalEven = 0;
double totalOdd = 0;
double averageWhole;
double averageEven;
double averageOdd;
System.out.println("Generating Numbers:");
for (int Repeater = 0; Repeater < 10; Repeater++) {
number = Generate.nextInt(100);
List.add(number);
}
System.out.println("Loaded... " + "Putting Numbers Into List");
System.out.println();
for(int Insert = 0; Insert < 3; Insert++) {
System.out.println("Adding To List...");
}
System.out.println("List Completed!");
System.out.println();
System.out.println();
for (int x = 0; x < List.size(); x++) {
total += List.get(x);
//Complicated Code --- really big for loop try to simplify later.
if (List.get(x) % 2 == 0) {
Even.add(List.get(x));
}
else {
Odd.add(List.get(x));
}
}
System.out.println("Your Total Is: " + total);
System.out.println();
System.out.println();
System.out.println("Even Numbers:" + "\t" + "Odd Numbers");
for (int Output = 0; Output < Even.size() && Output < Odd.size(); Output++)
{
System.out.println(Even.get(Output) + "\t" + "\t" + Odd.get(Output));
}
averageWhole = total / List.size();
System.out.println("Average of All Numbers: " + "Average of All Even Numbers: "+ "Average of all Odd Numbers: " );
for (int averageE = 0; averageE < Even.size(); averageE++) {
totalEven = totalEven + Even.get(averageE);
}
averageEven = totalEven / Even.size();
for (int averageO = 0; averageO < Odd.size(); averageO++) {
totalOdd = totalOdd + Odd.get(averageO);
}
averageOdd = totalOdd / Odd.size();
System.out.print(averageWhole + "\t" + "\t" + "\t" + " " + averageEven + "\t" + "\t" + "\t" + "\t" + " " + averageOdd);
System.out.println();
System.out.println();
System.out.println("Command Complete...");
Sorry for it being so compacted - learning java - 2/3 weeks in -- Thanks!
When you are printing the odd and even numbers the condition in the loop will be met when the shorter list will be done, so the printing stops before printing all the numbers. You separate the printing to two separate loops.
for (int i = 0; i < Even.size(); i++) {
System.out.println(Even.get(i));
}
for (int i = 0; i < Odd.size(); i++) {
System.out.println(Odd.get(i));
}
As a side note, variables in Java should start with lowercase. Even, Odd, Output etc should be even, odd, output.
Another alternative to Guy's code that keeps the same format:
for (int Output = 0; Output < Even.size() || Output < Odd.size(); Output++) {
String even = "-";
if(Output < Even.size()){
even = Even.get(Output).toString();
}//end of if
String odd = "-";
if(Output < Odd.size()){
odd = Odd.get(Output).toString();
}
System.out.println(even + "\t" + "\t" + odd);
}

How can i position the colums in my matrix evenly?

package SinemaSalonu;
public class SinemaSalonu {
public static void main(String args[]) {
int[][] matrix = new int[10][20];
for (int k = 0; k < 10; k++) {
matrix[k][0] = k + 1;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(" " + matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\n\n" + " " + "P E R D E");
}
}
when i run this code the resulting matrix' last row is not centered with others cause of the number "10" in the last row. it caused the row to slightly shift to the right. i want to fix this and center each row.
In order to align the lines with a single digit with the lines that start with two digit replace your printing:
System.out.print(" " + matrix[i][j] + " ");
with:
int n = matrix[i][j];
System.out.print(" " + (n < 10 ? " " + n : n) );
It will add an extra space before each line that starts with a single digit.
It will look like this:

2 Dimensional Array in Java Output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having a hard time outputting the the average of each row in this array that I'm trying to run:
int x, y, val;
double sum=0, ave, sumtot;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
}
sumtot = sum;
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Hope you guys can help me with this.:)
You might want to try out is something like this (with slightly cleaned up code). If you need to store the data for averages of each row rather than just printing them on fly, you could add them into an array or arraylist.
double sum=0, ave;
int x = khel.nextInt();
int y = khel.nextInt(); // input for array sizes
int val = x * y;
double rowSum; // something to contain data
double[][] myArray = new double[x][y];
for(int i=0; i < myArray.length; i++)
{
for(int j=0; j < myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble(); // input for array content
}
}
for(int i=0; i < myArray.length; i++)
{
rowSum = 0; // reset value each row
for(int j=0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + "\t");
sum += myArray[i][j];
rowSum += myArray[i][j]; // add value from array
}
System.out.println(rowSum / (double)myArray[i].length); // print average from each row
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
// this is the average of the whole table
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Review the logic of this and apply it in your code (assume that array[5][5] already has values)...
for( int row = 0; row < 5; row++ )
{
int rowSum = 0;
for( int column = 0; column < 5; column++ )
{
rowSum += array[row][column];
}
System.out.println( String.format( "Sum of values in row %d: %d", row, rowSum ) );
System.out.println( String.format( "Average of values in row %d: %d\n", row, ( rowSum / 5 ) ) );
}
If you just want to output the average per row, editing from what you current have. You can do this:
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
rowSum += myArray[i][j]; //Calculate sum of each row
}
System.out.println("Avg for row " + (i+1) + ":" + rowSum/(double)myArray.length);
rowSum = 0; //reset value for calculation for next row
}
Take note of where I placed the println() statement. Placing it after the inner loop will ensure it prints after all column values are added in each row.
I finally got it! Thank you for all your output guys!:) It drew closer to getting it right.:) Here's how I did it:
int x, y, val, i, j, row=1;
double sum=0, ave, rowSum;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(i=0; i<myArray.length; i++)
{
for(j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(i=0; i<myArray.length; i++)
{
rowSum = 0;
for(j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
rowSum = rowSum + myArray[i][j];
}
rowSum = rowSum / myArray[i].length;
System.out.println("");
System.out.println("The average of the row " + row + " is " + rowSum + ".");
row++;
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
}
}
Your inputs helped me a lot. Thanks a bunch.:)

How to multiply the elements of a column in a 2D array in Java?

i have a 2D array 3X5 and i need the to multiply each element in column one, and so forth. This is what ive attempted without any luck. the result is not correct. i tried storing each column into an array and multiply each element from that array but i get the same results.
edit: yes i am aware there is no multiplication in this code, that is because it yields an incorrect product.
for(int j = 0; j < 5; j++){
double v = 0.0;
double[] ex = new double[3];
double volumeBox1 = 0.0;
for(int i = 0; i < 3; i++){
v = d[i][j];
System.out.println(v);
for(int z = 0; z < 3; z++){
ex[z] = v;
}
}
System.out.println("The volume of box " + (j+1) + " is: " + volumeBox1);
I will assume your matrix is 5 x 3, which is more logical and convenient than 3 x 5 for this use case :
for (int i = 0 ; i < d.length ; j++) {
double vol = 1;
for (int j = 0 ; j < d[i].length ; j++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}
This can of course be done with a 3 x 5 matrix but I think it makes less sense to iterate on the columns :
for (int j = 0 ; j < d[0].length ; j++) {
double vol = 1;
for (int i = 0 ; i < d.length ; i++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}

Categories

Resources