KTF
KTF

Reputation: 317

ArrayList Output Error

I'm trying to make a program that will ask for a number of people to go into an ArrayList and then pick a name out of it randomly. The code is working fine but the string asking for name input displays itself twice the first time you run it. Any clue why this happens?

What I want it to display: Enter a name: ......

What it displays: Enter a name: Enter a name: ......

import java.util.*;

class RandomNumGen
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        Random random = new Random();

        ArrayList<String> names = new ArrayList<String>();

        int a, b;

        System.out.print("\nEnter the number of people: ");
        a = input.nextInt();
        System.out.println();

        for (int i = 0; i <= a; i++)
        {
            System.out.print("Enter a name: ");
            names.add(input.nextLine());
        }

        b = random.nextInt(a);
        System.out.print("\nRandom name: " +names.get(b)+ "\n");
    }
}

Upvotes: 1

Views: 74

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34146

The issue is that nextInt() just consumes an integer, but not the new-line character inputted when you press Enter.

To solve this you can add

input.nextLine();

after the call to nextInt() so it consumes the new-line character.

Another option would be reading a whole line, and then parsing its content (String) to a int:

a = Integer.parseInt(input.nextLine());

Upvotes: 2

Related Questions