0

I started learning Java and I just finished installing IntelliJ on my office laptop but I'm facing a weird problem.

I'm trying to read the elements from a string using the Scanner but the Scanner is not reading the first element, a[0] and i dont know why. Here is my code:

import java.util.Scanner;

public class Exercise15 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("length of the string n= ");
        int n=s.nextInt();
        String[] myArray = new String[n];
        System.out.println("Elements to store in the array: ");
        for (int i = 0; i < n; i++) {
            System.out.println("Enter the name ");
            myArray[i]=s.nextLine();
        }
        for (int i = 0; i < n; i++) {
            System.out.println(i);
            System.out.println("Hello " + myArray[i]);
        }
    }
}

for n =3, it's always reading only 2 elements. Anybody has any idea why this is happening ?

Z3tMeN
  • 1
  • for some reason the scanner is not skipping anymore after I used the following command : s.nextLine() right before the first "for". I just don't understand why, can somebody explain ? – Z3tMeN Dec 01 '20 at 13:08

0 Answers0