0

The purpose of this application is to get the full name of a user, and split them up. The results are printed.

if(nameParts.length < 2|| nameParts.length > 3) is somehow gaining control from the loop after it runs a 2nd time or beyond. I would assume that name and nameParts should be getting values assigned to them once again. Why is this happening, and how can I fix this?

   public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);
            String choice = "y";

            System.out.println("Welcome to the name parser.\n");

            while(choice.equalsIgnoreCase("y")) {

                System.out.print("Enter a name: ");

                String name = sc.nextLine();
                String[] nameParts = nameSeperate(name);

                if(nameParts.length < 2|| nameParts.length > 3) {
                    System.out.println("Please enter your full name or your first and last name.");
                    continue;
                }
                else if(nameParts.length == 2) {
                    System.out.println("First Name: " + nameParts[0]);
                    System.out.println("Last Name: " + nameParts[0]);
                }
                else {
                    System.out.println("First Name: " + nameParts[0]);
                    System.out.println("Middle Name: " + nameParts[1]);
                    System.out.println("Last Name: " + nameParts[2]);
                }
                System.out.println("Would you like to enter another name? (y/n)");    
                choice = sc.next();
            }            
        }

Here is the output:

Welcome to the name parser.

Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
y
Enter a name: Please enter your full name or your first and last name.
Enter a name: Alfons Pineda
First Name: Alfons
Last Name: Pineda
Would you like to enter another name? (y/n)
n
user3758041
  • 179
  • 1
  • 11
  • If you use `choice = sc.nextLine();` instead of `next()` does the problem go away? I suspect that `next()` grabs the character but leaves the newline in the buffer for the next call to `nextLine()` to grab before you even have a chance to enter anything. – Grambot Jun 19 '14 at 22:20
  • I do not believe that this was a duplicate, because I had no idea this was the fault of the Scanner. – user3758041 Jun 19 '14 at 22:31

1 Answers1

0

I am not sure, but for your first scan you use sc.nextLine() and for the second one just sc.next(). Maybe using sc.nextLine() also for the second statement would help. It could be, that the \n was not read by sc.next().

Therefore in the second loop only the newline would be read by the first scan.

Alex VII
  • 930
  • 6
  • 25