在方法内部执行do-while循环

时间:2015-05-09 06:52:58

标签: java loops

我在这个代码示例中一切正常,但每次在输出屏幕上调用do-while循环时,它都会跳过" First name"输入,并直接进入"你多大了?"输入。为什么会发生这种情况,我该如何解决?我希望能够重复整个事情而不会跳过"名字"当我选择' y'执行循环。

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');

        }
    }

2 个答案:

答案 0 :(得分:1)

请注意:

  • String java.util.Scanner.next() - 返回:下一个标记
  • String java.util.Scanner.nextLine() - 返回:跳过的行

更改您的代码[在初始行时执行]如下所示:

    System.out.println("First Name: ");
    inputFn = keyboard.next();

答案 1 :(得分:0)

使用keyboard.next()代替.nextLine()。有关更多信息,请查看Java API中有关Scanner类的信息。 nextLine()

  

使此扫描仪超过当前行并返回跳过的输入。"