0

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);
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
rhucha
  • 1
  • 2
    `int m[][] = new int[r][c];` creates a new matrix but makes it local to that method. I think you wanted to assign that new matrix to the instance's `m`, so that would be done like `m = new int[r][c];`. – Federico klez Culloca Sep 19 '22 at 16:37
  • And hint: whoever tells you to use such super short variable names: don't do that. Code is written so that HUMAN readers can easily read, understand and actually pronounce it. So: use names that MEAN something to the reader, and make sure that the name matches the actual usage in the source code. – GhostCat Sep 19 '22 at 16:44

0 Answers0