Matrix Multiplication, Index Out of Bounds Exception - java

I have try to create a code that can solve a matrix.
import java.util.Scanner;
public class Pratical_8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking A Matrix
System.out.println("Enter number of Rows and Column for first Matrix");
System.out.print("Enter Rows ");
int aRLen=sc.nextInt();
System.out.print("Enter Columns ");
int aCLen=sc.nextInt();
int [][] a = new int [aRLen][aCLen];
System.out.println("Enter Matrix");
for(int i=0;i<aRLen;i++)
{
for(int j=0;j<aCLen;j++)
{
a[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Taking B Matrix
System.out.println("Enter number of Rows and Column for second Matrix");
System.out.print("Enter Rows ");
int bRLen=sc.nextInt();
System.out.print("Enter Columns ");
int bCLen=sc.nextInt();
int [][] b = new int [bRLen][bCLen];
System.out.println("Enter Matrix");
for(int i=0;i<bRLen;i++)
{
for(int j=0;j<bCLen;j++)
{
b[i][j]=sc.nextInt();
}//End of j loop
}//End of I loop
// Creating resulting Matrix
int [][] r = new int [aRLen][bCLen];
// Check for Valid input
if(aCLen!=bRLen)
{
System.out.println("Error invalid input");
System.out.println("Multiplication of this matrix is not possible");
}
else
{
for(int i=0;i<aCLen;i++)
{
for(int j=0;j<bRLen;j++)
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
}//End of if-else
}//End of main
}//End of class
it have an error after sucessfully give an output
Output:-
Enter number of Rows and Column for first Matrik
Enter Rows 1
Enter Columns 3
Enter Matrix
1
2
3
Enter number of Rows and Column for second Matrix
Enter Rows 3
Enter Columns 1
Enter Matrix
1
2
3
14
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Pratical_8.main(Pratical_8.java:57)
Process finished with exit code 1
This Error only ocure in non Sysmetrix Matrix
What is the PROBLEM?

Since the final matrix is of order aRLen x bCLen the last for loops needs to be modified.
for(int i=0;i<aRLen;i++) // Instead of aClen
{
for(int j=0;j<bCLen;j++) //Instead of bRlen
{
for(int k=0; k<bRLen;k++)
{
r[i][j] += a[i][k] * b[k][j]; // LINE 57 ERROR
}//End of k Loop
System.out.print(r[i][j]+" ");
}//End of j loop
System.out.println();
}//End of I loop
This will work properly.

Related

How can I print the sum of the columns as well?

package Matrix;
import java.util.Scanner;
public class Matrix
{
public static void main(String[] args) {
System.out.print("Enter 2D array size : ");
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int columns=sc.nextInt();
System.out.println("Enter array elements : ");
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=sc.nextInt();
}
}
System.out.print("\n \n");
for(int []x:twoD){
for(int y:x){
System.out.print(y+" ");
}
System.out.println();
}
System.out.println("");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
}
}
}
how can I print the sum of the columns as well?
here is what I have so far
My expected output must be :
5 9 8 = 22
3 8 2 = 13
4 3 9 = 16
___________
12 20 19
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
how can I print the sum of the columns as well? here is what I have so far, And it seems like there is a problem with my code as well. Hope you can help me. I've been working on this for days and I'm new to java.
You already have added up the elements in the row. Now to add up the columns instead of trying to change the row in your for loop change the columns to add up.
Change
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum=sum+twoD[i][j];
}
System.out.print(sum+" ");
sum=0;
System.out.print(" ");
To
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
Therefore you will have a loop that runs effectively for every column and has the sum at 0 in the beginning and at the accurate sum at the end of going through each column and all that is left is just to print it out.
If you want to have this implemented in JOption than instead of using Scanner in Java, you would have to import the JOption Library with this import statement
import javax.swing.JOptionPane;
Then you would change your input of 2D Array Size to using the method of showInputDialog. Remember that showInputDialog returns a String and so you would need to use parseInt to turn it to a Integer. Here is an example
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D Array
Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
Next change the input of the Array to also use this method. Like this
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
Resulting in the Final Code being
import javax.swing.JOptionPane;
public class Matrix{
public static void main(String[] args) {
int rows;
rows = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Rows : "));
int columns;
columns = Integer.parseInt(JOptionPane.showInputDialog("Enter 2D
Array Columns : "));
int twoD[][]=new int[rows][columns];
for(int i=0; i<rows;i++)
{
for(int j=0; j<columns;j++)
{
twoD[i][j]=Integer.parseInt(JOptionPane.showInputDialog("Enter
Array Elements for Row "+(i+1)+" Column "+(j+1)));
}
}
System.out.print("\n \n");
for(int []x:twoD){
int cSum = 0;
for(int y:x){
System.out.print(y+" ");
cSum+=y;
}
System.out.println(" = "+cSum);
}
System.out.println("");
System.out.println("___________");
for(int i=0;i<columns;i++) {
int sum = 0;
for(int j=0;j<rows;j++)
{
sum+=twoD[j][i];
}
System.out.print(sum+" ");
System.out.print(" ");
}
}
}

Square Matrix multiplication using Java

I'm trying to write a simple square matrix multiplication method using multidimensional arrays.
package matrixmultiplication;
import java.util.Scanner;
public class Matrixmultiplication
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] a,b,c;
int size;
System.out.print("Enter the Size of the matrix :");
size = scan.nextInt();
a=b=c=new int[size][size];
System.out.println("Enter the elements of the First matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element a[" + i +"]["+ j + "] : ");
a[i][j] = scan.nextInt();
}
}
System.out.println("Enter the elements of the Second matrix");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
System.out.print("Enter the element b[" + i +"]["+ j + "] : ");
b[i][j] = scan.nextInt();
}
}
System.out.println("The Product of the two matrix is : ");
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
int sum = 0;
for(int k=0;k<size;k++)
{
sum +=(a[i][k] * b[k][j]);
}
c[i][j] = sum;
System.out.print(c[i][j] + "\t");
}
System.out.println();
}
}
}
When I run this program in Netbeans ,I get the following output:
Enter the Size of the matrix :2
Enter the elements of the First matrix
Enter the element a[0][0] : 1
Enter the element a[0][1] : 1
Enter the element a[1][0] : 1
Enter the element a[1][1] : 1
Enter the elements of the Second matrix
Enter the element b[0][0] : 1
Enter the element b[0][1] : 1
Enter the element b[1][0] : 1
Enter the element b[1][1] : 1
The Product of the two matrix is :
2 3
3 10
The Correct output of this program should be :
2 2
2 2
Can someone tell me what is wrong with this code.
The problem is here:
a=b=c=new int[size][size];
This creates just one array, and makes all of the variables point to it. So, updating the elements of c is also updating the elements of a and b.
Create 3 arrays instead:
a=new int[size][size];
b=new int[size][size];
c=new int[size][size];
Ideone demo

I am only able to print up to "red: 1" only, after which my program ends due to usage of break statement

Please see this code:
import java.util.Scanner;
public class Array
{
public static void main(String args[])
{
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++)
{
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
Scanner scan2=new Scanner(System.in);
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextLine();
}
OUTER:
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":");
break OUTER;
}
INNER:
for (int l = 0; l < numbers.length; l++)
{
System.out.println(numbers[ l ]);
break INNER;
}
}
}
I am a newbie, learning Array as of now, in Java. I want to print the outcome of the code above as follows:
Enter 5 numbers:
//Say:
RED
GREEN
BLUE
PINK
YELLOW
Enter 5 numbers:
1
2
3
4
5
//Output of the code should be:
RED: 1
GREEN: 2
BLUE: 3
PINK: 4
YELLOW: 5
How can I print the array? I am only able to print up to "RED: 1" only, after which my program ends due to break statement.
Your last for does not a have any purpose. Just try :
import java.util.Scanner;
public class Array {
public static void main(String args[]) {
String[] names=new String[5];
Scanner scan=new Scanner(System.in);
System.out.println("Enter 5 colour:");
for(int i=0; i<names.length;i++){
names[i]=scan.nextLine();
}
String[] numbers=new String[5];
System.out.println("Enter 5 numbers:");
for(int j=0; j<numbers.length;j++) {
numbers[j]=scan.nextLine();
}
for (int k = 0; k < names.length; k++){
System.out.println(names[ k ] + ":"+ numbers[k]);
}
}
}
ANd it's stop at the first because you break your for
scan.nextLine() reads the whole line of input that is it reads until you don't enter \n new line charachter, so use nextInt() instead of that. Also each System.out.println() is used to print a whole line so only one loop can be used. If names and numbers have same length. And change numbers[] from String to int, that would be more type safe.
int numbers[] = new int[5];
for(int j=0; j<numbers.length;j++)
{
numbers[j]=scan.nextInt();
}
for (int k = 0; k < names.length; k++)
{
System.out.println(names[ k ] + ":" + numbers[k]);
}
Since the number of elements be it color or numericals that you're trying to get from the user is fixed here i.e 5, why complicate things? Use a single for loop to print all the contents of both the arrays:
for(int k=0;k<names.length;k++){
System.out.println(names[k] + ":"+numbers[k]);
}

User Input java 2d Array

I need to create code that takes user input to create the size of the 2d array (rows and columns must be less than 6), then fill it up with values that the user gives (between -10 and 10). My loop for taking the values isn't working at all and I'm not sure why. Here's the code
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
// create loop for accepting values within the matrix
// first loop for row values
for (int i = 0; i < userArray.length; i++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix rows");
int rowValues = input.nextInt();
while (rowValues > 10 || column < -10) {
System.out.println(
"Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
rowValues = input.nextInt();
}
// second embedded loop for column values
for (int j = 0; j < userArray[i].length; j++) {
System.out.println("Please enter numbers between -10 and 10 for your matrix columns");
int columnValues = input.nextInt();
while (columnValues > 10 || column < -10) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter a number between 10 and -10.");
columnValues = input.nextInt();
}
}
}
printMatrix(userArray);
}
Couple of things here. First, your for-loop has two separate loops for the rows and columns. I assume what you're going for is prompting the user for each individual cell of the 2D array, which would require two nested loops. Second, at no point does your code example assign the user input to a variable, so I presume your output is just a bunch of 0 values?
You're probably looking for something more like this:
for (int i = 0; i < userArray.length; i++)
for(int j = 0; j < userArray[i].length; j++)
{
System.out.println("Please enter numbers between -10 and 10 for your matrix");
int valueIn = input.nextInt();
while (valueIn > 10 || valueIn < -10)
{
System.out.println("Sorry. Your number is not the correct size. " + "Please enter a number between 10 and -10.");
valueIn = input.nextInt();
}
userArray[i][j]=valueIn;
}
You need a nested loop, to read values at row and then column level.
Something like below:
import java.util.Scanner;
public class Matrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Implement scanner
Scanner input = new Scanner(System.in);
// create loop for accepting matrix input
// first accept row size
System.out.println("Please enter the number of rows in your matrix. Must be 5 or less.");
int row = input.nextInt();
while (row > 5 || row < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of rows in your matrix. Must be between 5 and 1.");
row = input.nextInt();
}
// next accept column size
System.out.println("Please enter the number of columns in your matrix. Must be 5 or less.");
int column = input.nextInt();
while (column > 5 || column < 1) {
System.out.println("Sorry. Your number is not the correct size. "
+ "Please enter the number of columns in your matrix. Must be between 5 and 1.");
column = input.nextInt();
}
// declare array with row and columns the user gave
int[][] userArray = new int[row][column];
for(int i=0;i< row ; i++){
for(int j=0; j< column; j++) {
System.out.print("Please enter the value for array["+i+"]["+j+"] (between -10 and 10):");
int val = input.nextInt();
if(val>10 || val< -10) {
System.out.println("Invalid value.");
continue;
}
userArray[i][j] = val;
}
}
printMatrix(userArray, row, column);
}
public static void printMatrix(int[][] array, int row, int column) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
public class Matrix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of rows.");
int rows = getValueFromConsole(scan, 1, 5);
System.out.println("Enter number of columns.");
int cols = getValueFromConsole(scan, 1, 5);
System.out.println("Enter matrix data.");
int[][] matrix = createMatrix(scan, rows, cols, -99, 99);
printMatrix(matrix);
}
private static int[][] createMatrix(Scanner scan, int rows, int cols, int min, int max) {
int[][] matrix = new int[rows][cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
matrix[row][col] = getValueFromConsole(scan, min, max);
return matrix;
}
private static int getValueFromConsole(Scanner scan, int min, int max) {
while (true) {
System.out.format("Number [%d:%d]: ", min, max);
int val = scan.nextInt();
if (val >= min && val <= max)
return val;
System.out.println("Sorry. Your number is not correct. Try again.");
}
}
private static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.format("%4d", matrix[row][col]);
System.out.println();
}
}
}
Output:
Enter number of rows.
Number [1:5]: 3
Enter number of columns.
Number [1:5]: 3
Enter matrix data.
Number [-99:99]: 10
Number [-99:99]: -11
Number [-99:99]: 12
Number [-99:99]: -13
Number [-99:99]: 14
Number [-99:99]: -15
Number [-99:99]: 16
Number [-99:99]: -17
Number [-99:99]: 18
10 -11 12
-13 14 -15
16 -17 18

Printing a Square Matrix and Transposing it with Java

I need to write a program that will take a number n from the user and create an nxn matrix that counts up, then I need to transpose it. I've tried multiple methods of coding, but nothing displays correctly.
import java.util.Scanner;
public class SquareMatrix {
public static void main(String[] args)
{
//Variables
int size;
int value;
//Scanner
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Prompt
System.out.println("Enter the size of the Square Matrix: ");
size = input.nextInt();
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = i+j;
System.out.print(value);
}
}
}
}
The result I'm currently getting is:
Enter the size of the Square Matrix:
3
123
234
345
I need it to look more like this:
Enter the Size of the Square Matrix:
3
Square Matrix:
1 2 3
4 5 6
7 8 9
Transpose:
1 4 7
2 5 8
3 6 9
The nxn matrix counting up is
for(int i=0; i<size; i++) {
System.out.println();
for(int j=1; j<=size; j++) {
value = j + i*size;
System.out.print(value);
}
}
The transponse is
for(int i=1; i<=size; i++) {
System.out.println();
for(int j=0; j<size; j++) {
value = j*size + i;
System.out.print(value);
}
}
I wrote a code that does exactly what you need. It may seem overcomplicated but i think it grasp the idea that you would do with pencil and paper. You need to put the scanning user input part in though.
int n=10;
int[][] matrix =new int[n][n]; // a 2D array as one would imagine a matrix
int num=0;
int temp=0;// used in transposing
//initializing the arrays of the second dimension
for (int init=0;init<n;init++){
matrix[init]=new int[n];
}
System.out.println("filling and printing matrix");
for (int fill_row=0;fill_row<n;fill_row++){
for(int columns=0;columns<n;columns++){
matrix[fill_row][columns]=++num;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[fill_row]));
}
}
}
System.out.println("Transposed matrix");
for (int transp_row=0;transp_row<n;transp_row++){
for(int columns=transp_row;columns<n;columns++){
//store actual value to temp,
temp=matrix[transp_row][columns];
//by switching the order of the indicies assign new value to current position
matrix[transp_row][columns]=matrix[columns][transp_row];
//assgin temp value to what we used as replacement
matrix[columns][transp_row]=temp;
if(columns==n-1){
System.out.println(Arrays.toString(matrix[transp_row])); // print each rows of the array
}
}
}
}
I hope it helps.

Categories