0

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".

1
  • 3
    Java naming conventions have variables and methods starting with a lower case letter (x, y). Commented Sep 27, 2020 at 23:00

1 Answer 1

1

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));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. this really helped and worked as needed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.