0

i have to build a 2D array that ask user to enter numbers to build the 2D array i know how to build this array using the for loop. But here i want to use the user input.

so anyone can help me ??

after i tried to run this program it display this error :

enter the elementss for the Matrix
Exception in thread "main" java.lang.NullPointerException
    at test7.test7.fill(test7.java:29)
    at test7.test7.main(test7.java:41)

this is my code:

package test7;

import java.util.Scanner;

public class test7 {

    private int row = 4;
    private int col = 4;
    private int[][] matrix;

    public test7(int trow, int tcol) {

        this.row = trow;
        this.col = tcol;
    }

    public test7(int trow, int tcol, int[][] m) {

        this.row = trow;
        this.col = tcol;
        this.matrix = m;
    }

    public int[][] fill(){

        System.out.println("enter the elementss for the Matrix");
        Scanner in = new Scanner(System.in);
        int[][] data = new int[0][0];
        for(int i = 0; i< matrix.length; i++){
            for(int j = 0 ;j< matrix[i].length; j++){
                int x = in.nextInt();
            }

        }
        return data;
    }

    public static void main(String[] args){

        Question2 q2 = new Question2(3, 2);
        q2.fill();
    }
}
2
  • The error is in your Question2 class. can you post the code of this class too?? Commented Dec 24, 2014 at 9:35
  • sorry i have changed the name of the package and the name of the class i edit my question..sorry again Commented Dec 24, 2014 at 9:39

3 Answers 3

1

Need to do this

   public static void main(String[] args){

    int[][] ma=new int[3][2];
    test7 q2 = new test7(3, 2,ma);
    q2.fill();
}

Instead of this

   public static void main(String[] args){

    Question2 q2 = new Question2(3, 2);
    q2.fill();
}

Reason

You are not initializing your matrix any where that is why getting the error.

Sign up to request clarification or add additional context in comments.

Comments

0

declare your int[][] data array with what size you want. try this:

public test7(int trow, int tcol) { this.row = trow; this.col = tcol; this.matrix = new int[trow][tcol]; }

Comments

0

That's because you are declared matrix without initializing it : private int[][] matrix;, So, it's null now, as the constructor sets only the value of row and col, try to initialize it using the other constructor:

     Question2 q2 = new Question2(3, 2, new int[3][2]);

or give it the value in the first constructor execution:

public Question2(int trow, int tcol) {

    this.row = trow;
    this.col = tcol;
    this.matrix = new int[trow][tcol];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.