1

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");
    }
}
0

1 Answer 1

2

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.