javaarraysinput

User input to 2 separate arrays in Java


What I want to do is to add 2 elements per line into 2 separate arrays. The first element goes to the X array and the second element goes to the Y array.

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    int n = Integer.parseInt(reader.readLine());

    double[] X = new double[n];
    double[] Y = new double[n];

    String[] elem = reader.readLine().split(" ");
    for (int i = 0; i < n; i++) {
        X[i] = Integer.parseInt(elem[n]);
        Y[i] = Integer.parseInt(elem[n]);
    }
    System.out.println(X, Y);
}

input:

3 4
1 1
2 3

where the first column is array X and the second column is array Y. I played with code several times but it still gives me: "Index 2 out of bounds for length 2".


Solution

  • You have to read your lines inside the for loop. X[i] corresponds to elem[0]; Y[i] corresponds to elem[1]. For example:

    import java.io.*;
    import java.util.*;
    public class App {
        public static void main(String[] args) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            int n = Integer.parseInt(reader.readLine());
    
            double[] X = new double[n];
            double[] Y = new double[n];
    
            for (int i = 0; i < n; i++) {
                String[] elem = reader.readLine().split(" ");
                X[i] = Integer.parseInt(elem[0]);
                Y[i] = Integer.parseInt(elem[1]);
            }
            System.out.println(Arrays.toString(X));
            System.out.println(Arrays.toString(Y));
        }
    }