JAVA populates 2D array with user input

I am trying to populate an NxN matrix. What I would like to do is enter all the elements of a given string as one input. So, for example, if I have a 4x4 matrix, for each row, I would like to enter 4 columns in one input, and then print the matrix after each input, displaying the new values. I am trying to run the following code, but I get the error: Exception on 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 am prompted to enter 4 numbers, I enter the following:

1,2,3,4

      

Then I get the error.

+3


source to share


3 answers


You should simply 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();

      



Don't forget to close the scanner too!

+4


source


1 2 3 4 are not displayed by the scanner as double numbers, but as whole numbers.

So, you have the following possibilities:



  • If you don't need to double

    usenextInt()

  • Enter 1.0.2.0.3.0.4.0 instead of 1,2,3,4
  • Read the values ​​as strings and convert them to double

    usingDouble.parseDouble()

+2


source


I believe that it would be easier to use string.split()

, not .useDelimiter()

because when using a separator, you would have to enter the last number with a comma (since comma

this is one separator material) if you did not create some regular expression to take as a comma as a separator , and \n

.

Also, you must specify the prompt - System.out.print("Enter 4 numbers separated by comma: ");

inside the outer loop, not the inner loop, since you will be taking on every line inside the outer loop and only the elements on each line 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]);
   }
}

      

+2


source







All Articles