rhucha
rhucha

Reputation: 1

I have made a program in Java to accept and display a matrix but I am getting an ArrayIndexOutOfBoundsException

When I run the program, the accept method() runs smoothly but when I try to run the display() method, it shows an ArrayIndexOutOfBoundException: Index 0 out of bounds for length 0. I think it is because the values stored in matrix m are not passed to the display() method. What can I do?

package matrices;
import java.util.Scanner;

class Functions {
    int r,c,i,j,row,col;
    Scanner in = new Scanner(System.in);
    int m[][] = new int[r][c];
    
    void accept() {
        System.out.print("Enter no. of rows in the matrix : ");
        r = in.nextInt();
        System.out.print("Enter no. of columns in the matrix : ");
        c = in.nextInt();
        int m[][] = new int[r][c];
        System.out.print("Enter the elements : ");
        for (i=0; i<r; i++) {
            for (j=0; j<c; j++) {
                m[i][j] = in.nextInt();
            }
        }
    }
    
    void display() {
        for (int i=0; i<r; i++) {
            for (int j=0; j<c; j++) {
                System.out.print(m[i][j] + "  ");
            }
            System.out.print("\n");
        }
    }
}

public class Matrix {
    public static void main(String[] args) {
        int ch;
        Functions mat = new Functions();
        do {
            System.out.println("Menu\n1.Accept\n2.Display");
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter your choice : ");
            ch = sc.nextInt();
            switch(ch) {
            case 1: mat.accept();
                    break;
            case 2: mat.display();
                    break;
            }
        }while(ch<3);
    }
}

Upvotes: 0

Views: 38

Answers (0)

Related Questions