DeeTee DeeTee - 1 year ago 254
Java Question

JAVA populate 2D array with user input

I am trying to populate an NxN matrix. What I'd like to do is be able to enter all the elements of a given row as one input. So, for example if I have a 4x4 matrix, for each row, I'd like to enter the 4 columns in one input, then print the matrix after each input showing the new values. I try to run the following code but I get an error that reads: Exception in thread "main" java.util.InputMismatchException. Here is my code:

double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(",*");

for(i =0;i<4;i++){
System.out.print("Enter 4 numbers seperated by comma: ");
twoDm[i][j] = scan.nextDouble();


When I get the prompt to enter the 4 numbers I enter the following:


Then I get the error.

Answer Source

You should just do this;

double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(;
int i, j;

for (i = 0; i < 4; i++) {
  System.out.print("Enter 4 numbers seperated by comma: ");
  String[] line = scan.nextLine().split(",");
  for (j = 0; j < 4; j++) {
    twoDm[i][j] = Double.parseDouble(line[j]);



You should not forget to close the scanner too!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download