DeeTee DeeTee - 5 months ago 105
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(System.in).useDelimiter(",*");

for(i =0;i<4;i++){
for(j=0;j<4;j++){
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:

1,2,3,4


Then I get the error.

Answer

You should just do this;

double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(System.in);
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]);

  }
}

scan.close();

You should not forget to close the scanner too!