#java #массивы #исключения
есть метод, который заполняет одну строку двумерного массива с консоли.
на вход получает сам массив (Matrix) и его номер строки, которую будем заполнять.
хочу сначала проверить все ли числа в введенной строке. Если ввели не число, выдать
сообщение и начать считывать заново, но если ввести сюда что-то кроме чисел, программа
будет выводить сообщение в бесконечном цикле.
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;
}
Ответы
Ответ 1
Вот мой вариант с рекурсией, надеюсь будет полезен. 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)); }} десятичная часть вводиться после запятой.
Комментариев нет:
Отправить комментарий