简体   繁体   中英

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.

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!

1 2 3 4 are not visible by Scanner as double numbers, but as integers.

So you have the following possibilities:

  • If you don't need a double use nextInt()
  • Write 1.0,2.0,3.0,4.0 instead of 1,2,3,4
  • Read the values as strings and convert them to double with Double.parseDouble()

I believe it would be easier to use string.split() , rather than .useDelimiter() , because when using delimiter , you would have to input the last number with a comma as well (since comma is the one delimiting stuffs) unless you create some regex to take both comma and \\n as delimiter.

Also, you should give the prompt - System.out.print("Enter 4 numbers separated by comma: "); inside the outer loop, not the inner loop, since you would be taking in each row inside the outer loop, and only elements in each row in the inner loop.

You can do -

double twoDm[][]= new double[4][4];
int i,j = 0;
Scanner scan = new Scanner(System.in);
for(i =0;i<4;i++){
   System.out.print("Enter 4 numbers separated by comma: ");
   String row = scan.nextLine().split(",");
   for(j=0;j<4;j++){
      twoDm[i][j] = Double.parseDouble(row[j]);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM