0

Everything is working fine in this code sample that i did, but everytime it calls the do-while loop on the output screen, it skips the "First name" input, and goes straight to "How old are you?" input. why is that happening and how can i fix it? I want to be able to repeat the whole thing without skipping "First name" when i pick 'y' to perform the loop.

public class WeightGoalTest
    {
        public static void main(String[]args)
        {

            doWhile person = new doWhile();

            person.userInput(); 
        }
    }

    import java.util.*;

    public class doWhile
    {
        Scanner keyboard = new Scanner(System.in);

        private String inputFn = "";
        private int inputAge = 0; 
        private int inputHeight = 0;
        private double inputWeight = 0.0;
        private int inputCalculation = 0;
        private int inputGender = 0; 

        private char loop; 

        public void userInput()
        {

        do
        {
            System.out.println("First Name: ");
            inputFn = keyboard.nextLine();

            System.out.println("How old are you?");
            inputAge = keyboard.nextInt();

            System.out.println("Gender 1 - Male: ");
            System.out.println("       2 - Female: ");
            inputGender = keyboard.nextInt();

            System.out.println("What is your Height in inches? ");
            inputHeight = keyboard.nextInt(); 

            System.out.println("Current Weight in pounds: ");
            inputWeight = keyboard.nextDouble();

            System.out.println("\nDo you want to use the calculator again? (y/n)");
            loop = keyboard.next().charAt(0);

        }while(loop == 'y');

        }
    }
Mat
  • 188,820
  • 38
  • 367
  • 383
Olab
  • 7
  • 3
  • 1
    Classes in Java are **always** in `PascalCase`. Please stick to Java naming conventions if you post code here, and probably in general too. – Boris the Spider May 09 '15 at 07:07

2 Answers2

1

Please note:

  • String java.util.Scanner.next() - Returns:the next token
  • String java.util.Scanner.nextLine() - Returns:the line that was skipped

Change your code [do while initial lines] as below:

    System.out.println("First Name: ");
    inputFn = keyboard.next();
Rajesh
  • 2,120
  • 1
  • 10
  • 14
0

use keyboard.next() instead of .nextLine(). For further informations have a look in the Java API concerning the Scanner class. nextLine() will

Advance this scanner past the current line and return the input that was skipped."

Sebastian Walla
  • 1,086
  • 1
  • 9
  • 23