0

I'm a newbie to Java and here I am trying to minimize the amount of code I've written. I want to add elements to 2 arrays of the same size using only one for loop. I tried many ways but it ended up adding the same elements to both arrays. How can I loop twice and add different elements?

This's how I did it using two for loops...

public static void main (String[] args) throws IOException {

        BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));

        int size = Integer.parseInt(reader.readLine());
        int[] arr1 = new int[size];
        int[] arr2 = new int[size];
        String[] elem1 = reader.readLine().split("\\s+");
        for(int i = 0; i < size; i++)
        {
            arr1[i] = Integer.parseInt(elem1[i]);
        }


        String[] elem2 = reader.readLine().split("\\s+");
        for(int j = 0; j < size; j++)
        {
            arr2[j] = Integer.parseInt(elem2[j]);
        }

        System.out.println(LargestPair( arr1, arr2, size));
    }
1
  • I would just continue as you've gone. Commented Oct 23, 2020 at 15:19

2 Answers 2

1
String[] elem1 = reader.readLine().split("\\s+");
String[] elem2 = reader.readLine().split("\\s+");
for(int i = 0; i < size; i++)
{
    arr1[i] = Integer.parseInt(elem1[i]);
    arr2[i] = Integer.parseInt(elem2[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Something like the following should work:

 private static final Scanner SCANNER = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        System.out.print("Enter size of array: ");
        int size = Integer.parseInt(SCANNER.nextLine());

        Integer[] arr1 = getAsIntArray(size);
        Integer[] arr2 = getAsIntArray(size);

        System.out.println(LargestPair(arr1, arr2, size));
    }

    private static Integer[] getAsIntArray(int size) {
        System.out.print("Enter " + size + " space separated elements: ");
        return Arrays.stream(SCANNER.nextLine().split("\\s+"))
                .map(Integer::parseInt)
                .collect(Collectors.toList())
                .toArray(Integer[]::new);
    }

Is this what you meant?

1 Comment

Edited to use a more functional/concise approach

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.