2

I'm trying to create a program where the user can create an array using scanner. In this example, if the first input is 4, an array with the length of 4 is then initialized. However, in the next part, the scanner is asking for 5 inputs instead of 4. If the next inputs are 1 2 3 4 5, the final output will be [2,3,4,5]. I'm not sure why it's asking for 5 inputs instead of 4. Can someone tell me what I did wrong?

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);

        int n = s.nextInt();
        int[] numbers = new int[n];

        int input = s.nextInt();

        for (int i = 0; i < n; i++) {
            numbers[i] = s.nextInt();
        }

        System.out.println("---------");

        for (int x : numbers) {
            System.out.print(x);
        }
    }
}
1
  • 2
    Remove the line int input = s.nextInt(); . Commented Jun 29, 2018 at 13:48

1 Answer 1

2

The line int input = s.nextInt(); is consuming the first input.. that's why array is getting initialized from 2 at 0'th index.

Remove the line int input = s.nextInt(); and it'll work fine

Sign up to request clarification or add additional context in comments.

1 Comment

oh! I didn't realize that whoops. Thanks a lot!

Your Answer

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