Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How to solve this ERROR: Exception in thread \"main\" java.lang.IndexOutOfBounds

ID: 3722970 • Letter: H

Question

How to solve this ERROR: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.rangeCheck(ArrayList.java:657) at java.util.ArrayList.get(ArrayList.java:433)..

Here is JAVA code:

import java.io.*;
import java.util.*;
import java.util.stream.*;

   public class MartixMul{
      public static void main(String [] args){
       BufferedReader breader = null;
       BufferedWriter bwriter = null;
       FileWriter fwriter = null;
       List<Integer> mylist = new ArrayList<>();
  
       int row1,column1,row2,column2;
try {
        Scanner sc = new Scanner(new File("C:/Users/andrew/Desktop/New folder/jj.txt"));
         // adds numbers from .txt to ArrayList numbers

        while(sc.hasNextInt()){
         mylist.add(sc.nextInt());
        }
      }
       catch(FileNotFoundException e){
          System.err.println("Unable to find the file: fileName");
      }    
          row1 = mylist.get(0);
          column1 = mylist.get(1);
          row2 = mylist.get(2);
          column2 = mylist.get(3);

          if(column1 != row2){
           System.out.println("Column 1 is not equal to row 2. Matrix Multiplication is not possible.");
            try{
              fwriter = new FileWriter(new File("mytextfile.txt"));
              fwriter.write(String.format("Column 1 is not equal to row 2. Matrix Multiplication is not possible."));
              fwriter.close();
            }catch(Exception e){
              System.out.println("NONE");
            }
          }else{
          //checking to see if they hold the right numbers
          System.out.println("Matrix 1 has " + row1 + " rows and " + column1+ " columns");
          System.out.println("Matrix 2 has " + row2 + " rows and " + column2+ " columns");
          // This puts the first four numbers as the dimensions of int [][]
          int [][] matrix1 = new int [row1][column1];
          int [][] matrix2 = new int [row2][column2];

         // Removes the first four numbers from the List which are used as dimensions
          mylist.remove(0);
          mylist.remove(0);
          mylist.remove(0);
          mylist.remove(0);
          // This fills the matrix[][]'s up with the numbers in the List
          int iter = 0; // iterates the index of the List
          for( int row = 0; row < matrix1.length; row++){
             for( int col = 0; col < matrix1[row].length;col++){
              matrix1[row][col]= mylist.get(iter);
              iter++;
             }
           }
          for( int row = 0; row < matrix2.length; row++){
            for( int col = 0; col < matrix2[row].length;col++){
              matrix2[row][col]= mylist.get(iter);
              iter++;   
            }
          }
          System.out.println("The elements in Matrix 1 are:");
          System.out.println(Arrays.deepToString(matrix1));
          System.out.println("The elements in Matrix 2 are:");
          System.out.println(Arrays.deepToString(matrix2));

          int[][] multi = multiply(matrix1, matrix2);
          System.out.println("Product of Matrix 1 and Matrix 2 is: ");
          for (int i = 0; i < multi.length; i++) {
            for (int j = 0; j < multi[0].length; j++) {
                  System.out.print(multi[i][j] + " ");
                }
              }
try{
          fwriter = new FileWriter(new File("MatrixMultiplication.txt"));
          fwriter.write(String.format ("Matrix 1 has " + row1 + " rows and " + column1+ " columns"));
          fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format ("Matrix 2 has " + row2 + " rows and " + column2+ " columns"));
          fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format("The elements in Matrix 1 are:"));
          fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format(Arrays.deepToString(matrix1)));
          fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format("The elements in Matrix 2 are:"));
          fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format(Arrays.deepToString(matrix2)));
         fwriter.write(System.lineSeparator()); //new line
          fwriter.write(String.format("Product of Matrix 1 and Matrix 2 is: "));
          fwriter.write(System.lineSeparator()); //new line

               for (int i = 0; i < multi.length; i++) {
                 for (int j = 0; j < multi[0].length; j++) {
                   fwriter.write(String.format(multi[i][j] + " "));
                  }
                }                    
              fwriter.close();
      }catch(IOException ex) {
    ex.printStackTrace();
    }

      }
}
// Multiplication of matrix
     public static int[][] multiply(int[][] a, int[][] b)
     {
       int rowsInA = a.length;
       int columnsInA = a[0].length; // same as rows in B
       int columnsInB = b[0].length;
       int[][] c = new int[rowsInA][columnsInB];
       for (int i = 0; i < rowsInA; i++) {
         for (int j = 0; j < columnsInB; j++) {
           for (int k = 0; k < columnsInA; k++) {
              c[i][j] = c[i][j] + a[i][k] * b[k][j]; // Multiplication of matrices
            }
          }
       }
       return c;
     }
}

Explanation / Answer

Hi.. The problem with your input file your are giving to the java program. You need to give complete matrix in your input file.

MatrixMul.java

import java.io.*;
import java.util.*;
import java.util.stream.*;

public class MatrixMul{
public static void main(String [] args){
BufferedReader breader = null;
BufferedWriter bwriter = null;
FileWriter fwriter = null;
List<Integer> mylist = new ArrayList<>();
  
int row1,column1,row2,column2;
try {
Scanner sc = new Scanner(new File("C:/Users/andrew/Desktop/New folder/jj.txt"));
// adds numbers from .txt to ArrayList numbers

while(sc.hasNextInt()){
mylist.add(sc.nextInt());
}
}
catch(FileNotFoundException e){
System.err.println("Unable to find the file: fileName");
}   
row1 = mylist.get(0);
column1 = mylist.get(1);
row2 = mylist.get(2);
column2 = mylist.get(3);

if(column1 != row2){
System.out.println("Column 1 is not equal to row 2. Matrix Multiplication is not possible.");
try{
fwriter = new FileWriter(new File("mytextfile.txt"));
fwriter.write(String.format("Column 1 is not equal to row 2. Matrix Multiplication is not possible."));
fwriter.close();
}catch(Exception e){
System.out.println("NONE");
}
}else{
//checking to see if they hold the right numbers
System.out.println("Matrix 1 has " + row1 + " rows and " + column1+ " columns");
System.out.println("Matrix 2 has " + row2 + " rows and " + column2+ " columns");
// This puts the first four numbers as the dimensions of int [][]
int [][] matrix1 = new int [row1][column1];
int [][] matrix2 = new int [row2][column2];

// Removes the first four numbers from the List which are used as dimensions
mylist.remove(0);
mylist.remove(0);
mylist.remove(0);
mylist.remove(0);
// This fills the matrix[][]'s up with the numbers in the List
int iter = 0; // iterates the index of the List
for( int row = 0; row < matrix1.length; row++){
for( int col = 0; col < matrix1[row].length;col++){
matrix1[row][col]= mylist.get(iter);
iter++;
}
}
for( int row = 0; row < matrix2.length; row++){
for( int col = 0; col < matrix2[row].length;col++){
matrix2[row][col]= mylist.get(iter);
iter++;
}
}
System.out.println("The elements in Matrix 1 are:");
System.out.println(Arrays.deepToString(matrix1));
System.out.println("The elements in Matrix 2 are:");
System.out.println(Arrays.deepToString(matrix2));

int[][] multi = multiply(matrix1, matrix2);
System.out.println("Product of Matrix 1 and Matrix 2 is: ");
for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[0].length; j++) {
System.out.print(multi[i][j] + " ");
}
}
try{
fwriter = new FileWriter(new File("MatrixMultiplication.txt"));
fwriter.write(String.format ("Matrix 1 has " + row1 + " rows and " + column1+ " columns"));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format ("Matrix 2 has " + row2 + " rows and " + column2+ " columns"));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format("The elements in Matrix 1 are:"));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format(Arrays.deepToString(matrix1)));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format("The elements in Matrix 2 are:"));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format(Arrays.deepToString(matrix2)));
fwriter.write(System.lineSeparator()); //new line
fwriter.write(String.format("Product of Matrix 1 and Matrix 2 is: "));
fwriter.write(System.lineSeparator()); //new line

for (int i = 0; i < multi.length; i++) {
for (int j = 0; j < multi[0].length; j++) {
fwriter.write(String.format(multi[i][j] + " "));
}
}   
fwriter.close();
}catch(IOException ex) {
ex.printStackTrace();
}

}
}
// Multiplication of matrix
public static int[][] multiply(int[][] a, int[][] b)
{
int rowsInA = a.length;
int columnsInA = a[0].length; // same as rows in B
int columnsInB = b[0].length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j]; // Multiplication of matrices
}
}
}
return c;
}
}

Input:

jj.txt

3 3 3 3
1 2 3
4 5 6
7 8 9
1 4 5
1 3 4
1 2 3

In the top row of the input specifies rows and cols of both matrices. From the above i have given 3*3 matrix for both and i have given total 3*3(9)+ 3*3(9) = 18 numbers need to be entered in input.

Output:

Matrix 1 has 3 rows and 3 columns
Matrix 2 has 3 rows and 3 columns
The elements in Matrix 1 are:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The elements in Matrix 2 are:
[[1, 4, 5], [1, 3, 4], [1, 2, 3]]
Product of Matrix 1 and Matrix 2 is:
6 16 22 15 43 58 24 70 94

Please test the code and let me know any issues. Thank you. All the best.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote