0

I'm trying to write a code that asks a user to input their name, stores it in a List, then asks them to input their age, stores it in another list. It then asks the user if they would like to try again [Y/N]. When testing the code, I inputted "Y" and expected the loop to ask me to input another name. Instead, it skips through the name input and jumps to the age input. I can't figure out why. Here's the code

import java.util.ArrayList;
import java.util.Scanner;

public class PatternDemoPlus {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> ages = new ArrayList<Integer>();
        String repeat = "Y";
        while(repeat.equalsIgnoreCase("Y")){
            System.out.print("Enter the name: ");
            names.add(scan.nextLine());
            System.out.print("Enter the age: ");
            ages.add(scan.nextInt());

            System.out.print("Would you like to try again? [Y/N]");
            repeat = scan.next();
            //Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N]
            System.out.println(repeat);

            //Why is it that after the first iteration, it skips names.add and jumps right to ages.add?
        }
    }
}

I would appreciate your help. Thank you.

TheLebDev
  • 379
  • 2
  • 15
  • a hint: have you checked what is received at the line `repeat = scan.next()`? Pay attention in something like inputting "123 XYZ" as age. – Adrian Shum Sep 26 '16 at 06:04

1 Answers1

0

Using next() will only return what comes before a space. nextLine() automatically moves the scanner down after returning the current line.

Try to change your code like below.

    public class PatternDemoPlus {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> ages = new ArrayList<Integer>();
        String repeat = "Y";
        while(repeat.equalsIgnoreCase("Y")){
            System.out.print("Enter the name: ");
            String s =scan.nextLine();
            names.add(s);
            System.out.print("Enter the age: ");
            ages.add(scan.nextInt());
            scan.nextLine();
            System.out.print("Would you like to try again? [Y/N]");
            repeat = scan.nextLine();

            System.out.println(repeat);


        }
    }
}
Jekin Kalariya
  • 3,255
  • 2
  • 18
  • 31