0

So, I know this is probably a really stupid question, I am a beginner trying to learn Java basics and I have a problem with string array that I can't quite figure out. When I try to enter words into string array and the number of words is set by user (for example 5) I always can enter one less word (for example 4 instead of 5). My code is down below.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter the number of words");
    int n = scan.nextInt();
    String arr[] = new String[n];
    System.out.println("Please enter the words");
    for (int i = 0; i < arr.length; i++) {
        arr[i] = scan.nextLine();
    }

    for (int i = 0; i < arr.length; i++) {
        System.out.print(" " + arr[i]);
    }

}
  • What exactly is the behaviour? Do you get an `Exception`? If so: please [edit] the post and add the stack trace. --- Please format the code properly. – Turing85 Jan 08 '22 at 13:03
  • Well, I don't get an exception, for example if I type that the number of words is 4 and then when I try to enter the words, as I am entering after the third one the code goes to the next line, it prints out my array with only three elements. – Kristina Đukić Jan 08 '22 at 13:10
  • You may want to [edit] the post and add this information. – Turing85 Jan 08 '22 at 13:12
  • OK, will do, thanks. – Kristina Đukić Jan 08 '22 at 13:13

1 Answers1

0

It is because when you use nextInt(), it is not reading the newline character. You can avoid this using 2 approaches.

  1. Use nextLine i.e. use Integer.parseInt(scanner.nextLine()) instead of nextInt().

     int n = Integer.parseInt(scan.nextLine());
     String arr[] = new String[n];
    
  2. Call nextLine before for loop so that the redundant newline is consumed before your for loop.

     int n = scan.nextInt();
     String arr[] = new String[n];
     scan.nextLine();
     System.out.println("Please enter the words");
    
Tarun
  • 121
  • 7