0

I am trying to have a user input an int and then input that number of names.

The program prints those names backwards and in reverse order. However, the array where I am storing these names is always being created one element too small when I use Scanner. When I just assign a number myself, I don't have this problem. Is there something unique with Scanner or what am I doing wrong?

import java.util.Scanner;

class forTester {
    public static void main (String str[]) {
        Scanner scan = new Scanner(System.in); 

        //Why does this commented code scan only one less name than expected???
        /*
        System.out.println("How many names do you want to enter?");
        int num = scan.nextInt();
        System.out.println("Enter " + num + " Names:");
        String names[] = new String[num];
        */ 
        //Comment out the next two lines if you use the four lines above.
        System.out.println("Enter " + 4 + " Names:");
        String names[] = new String[4];

        // The code below works fine.
        for (int i = 0; i < names.length; i++) {
            names[i]=scan.nextLine(); 
        }

        for(int i = names.length - 1; i >= 0; i--) {
            for(int p = names[i].length() - 1; p >= 0; p--) {
                System.out.print(names[i].charAt(p));
            }
            System.out.println("");
        }
    }
}
ifloop
  • 8,079
  • 2
  • 26
  • 35
user835
  • 9
  • 1
  • 2

2 Answers2

1

Change commented code to :

   System.out.println("How many names do you want to enter?");
   int num = scan.nextInt();
   System.out.println("Enter " + num + " Names:");
   String names[] = new String[num];
   scan.nextLine(); // added this to consume the end of the line that contained
                    // the first number you read
Eran
  • 387,369
  • 54
  • 702
  • 768
1

The problem is that nextInt() leaves behind a new line character which will be gobbled by the nextLine() in the first iteration. So, you feel that the array size is one less. Actually, your first element of the array i.e, 0th index will have a new line character.

Your code should be :

  System.out.println("How many names do you want to enter?");
   int num = scan.nextInt(); // leaves behind a new line character
   System.out.println("Enter " + num + " Names:");
   String names[] = new String[num];
   scan.nextLine() // to read the new line character left behind by scan.nextInt()
TheLostMind
  • 35,966
  • 12
  • 68
  • 104