There is a method that fills one line of a two-dimensional array from the console. at the input it receives the array itself (Matrix) and its line number, which we will fill. I want to first check whether all the numbers in the input string. If you have entered not a number, issue a message and start reading again, but if you type in here something other than numbers, the program will display the message in an infinite loop.

public static double[][] read(double[][] Matrix,int StringNumber) { Scanner scanner = new Scanner(System.in); scanner.useDelimiter(";\\s*"); boolean isGood; double [] Mat = new double[Matrix.length]; do { isGood = true; for (int i = 0; i < Matrix.length; i++) { try { Mat[i] = scanner.nextDouble(); } catch (Exception e) { isGood = false; scanner.next(); } } if (isGood) { for (int i = 0; i < Matrix.length; i++) { Matrix[i][StringNumber] = Mat[i]; } } else { System.out.println("Вводите числа!!!!"); Zero(Mat); } }while (!isGood); return Matrix; } 
  • one
    You need to clear the input stream, still isGood will always be false if it gets into the exception at least once. After do you should put isGood = true; - Komdosh
  • isGood = true; - add after do { - Vartlok
  • scanner.nextDouble(); in the first cycle, they will eat all user input, but if the user enters everything correctly, he will have to repeat the input a second time. Either immediately fill in the matrix in the first cycle, and discard the second, or if you need to change the value in the matrix only if the user has successfully entered the entire line, save the input to a separate array, and then copy. - zRrr
  • implement another Komdosh advice: if you exclude, call scanner.next() , since if nextDouble() did not complete successfully, the scanner does not advance to the next element. It is also possible to change the cycles in some places - to require entering the number to infinity, and if the number is entered - to increase the column number - zRrr
  • Thank! the whole thing was that nextDouble () didn't go any further .. - Dmitry Vlasenko

1 answer 1

Here is my recursion option, I hope it will be useful.

 public class Number { public static double[][] read(double[][] matrix, int stringNumber) { Scanner scanner = new Scanner(System.in); try { for (int j = 0; j < matrix[stringNumber].length; j++) { System.out.print("Enter number: "); matrix[stringNumber][j] = scanner.nextDouble(); } } catch (Exception e) { System.out.println("error! make input again"); read(matrix, stringNumber); } return matrix; } public static void consoleOutput(double[][] matrix){ for (int i = 0; i < matrix.length; i++) { System.out.println(); for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } } } public static void main(String[] args) { double[][] matrix = new double[3][3]; consoleOutput(Number.read(matrix, 1)); }} 

the decimal part is entered after the comma.