Заполнить строки двумерного массива входными данными из строки - PullRequest
1 голос
/ 08 марта 2019

У меня есть следующая проблема: Значения каждой строки моей матрицы даны со столбцами, разделенными пробелами - поэтому я ввожу все значения строк в массив String, удаляю пробелы и анализирую числа в массив int. Теперь значения каждой строки выглядят как 1 число «12345», тогда как они должны быть «1 2 3 4 5».

Как я могу сначала разделить цифры, а затем заполнить матрицу, добавив элементы в каждую строку? Спасибо! Вот мой код:

    String n1 = input.nextLine ();
    int n = Integer.parseInt(n1); //rows of the matrix
    String[] arr = new String [n]; //contains all the rows of the matrix
    int [] array = new int [arr.length]; // contains all the elements of the rows of the matrix without whitespace

    for (int i = 0; i < arr.length; i++) {
        arr [i] = input.nextLine().replaceAll("\\s+","");
        array[i] = Integer.parseInt(arr[i]);
    }

    int matrix [][] = new int [n][arr[0].length()];

Ответы [ 3 ]

1 голос
/ 08 марта 2019

Здесь у вас есть важные вопросы:

for (int i = 0; i < arr.length; i++) {
    arr [i] = input.nextLine().replaceAll("\\s+",""); // loses the separator between the number
    array[i] = Integer.parseInt(arr[i]); // makes no sense as you want get all numbers submitted for the current row and no a single one
}

Вы можете выполнить обработку, используя намного меньше переменных, если заполните матрицу в каждой представленной строке.
Нет проверенного кода, но вы должны понять.

String n1 = input.nextLine();
int n = Integer.parseInt(n1); //rows of the matrix  

int matrix [][] = null; // init it later : as you would have the two dimensions knowledge

for (int i = 0; i < n; i++) {
    String[] numberToken = input.nextLine().split("\\s"); 

    // matrix init : one time
    if (matrix == null){ matrix [][] = new int[n][numberToken.length]; }

    // array of int to contain numbers of the current row
    int[] array = new int[numberToken.length];

    // map String to int. Beware exception  handling that you should do
    for (int j = 0; j < numberToken.length; j++){
        array[j] = Integer.parseInt(numberToken[j]); 
    }
    // populate current row of the matrix
    matrix[i] = array[j];
}
1 голос
/ 08 марта 2019

Трудно сказать, но, как я понимаю, вы пытаетесь вводить матрицу построчно через сканер. Это может решить вашу проблему.

    Scanner scanner = new Scanner(System.in);
    //number of rows
    int n = Integer.parseInt(scanner.nextLine());
    int[][] matrix = new int[n][];
    for(int i=0;i<n;i++) {
        String line = scanner.nextLine();
        String[] numbers = line.split(" ");
        matrix[i] = new int[numbers.length];
        for(int j=0;j<numbers.length;j++) {
            matrix[i][j] = Integer.parseInt(numbers[j]);
        }
    }
1 голос
/ 08 марта 2019

Вы должны split() ввести строку с каким-либо символом (пробел в вашем примере).

Пример того, как преобразовать String в массив String (используя метод split())

// Example input
String input  = "1 2 3 4 5";

// Split elements by space
// So you receive array: {"1", "2", "3", "4", "5"}
String[] numbers = input.split(" ");

for (int position = 0; position < numbers.length; position++) {
    // Get element from "position"
    System.out.println(numbers[position]);
}

Пример, как преобразовать String в массив int

// Example input
String input = "1 2 3 4 5";

// Split elements by space
// So you receive array: {"1", "2", "3", "4", "5"}
String[] strings = input.split(" ");

// Create new array for "ints" (with same size!)
int[] number = new int[strings.length];

// Convert all of the "Strings" to "ints"
for (int position = 0; position < strings.length; position++) {
    number[position] = Integer.parseInt(strings[position]);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...