用户输入如果声明失败,我不知道原因

时间:2014-04-25 01:50:37

标签: java algorithm loops

我的程序正在计算并根据用户的年龄,身高,体重和性别打印用户的BMR值。

但是,在根据输入检查性别时,我的程序无效,并直接跳到else语句。 这是我的代码到目前为止,我该如何解决?

import java.util.Scanner;
public class MaintainingWeight
{
    public static void main(String[] args) 
    {
        //Instance Variables
        int age, weight, inches; //weight in pounds, height inches
        double BMR;
        String gender;

        //Program Introduction Welcoming the user
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Hello fellow user, this program will help determine \nyour BMR value and tell the amount of chocalate bars you will need");
        System.out.println("in order to maintain your body weight.");

        //Ask the User to input their age, weight and height
        System.out.println("Please enter your age.");
        age = keyboard.nextInt();

        System.out.println("Next enter your weight in pounds");
        weight = keyboard.nextInt();

        System.out.println("Now enter your height by inches\n (Reminder: to find your height in inches mutiply your height by feet to 12.000. (feet * 12.000))");
        inches = keyboard.nextInt();

        //Tell the user their gender then print their BMR Value
        System.out.println("Please enter your gender. Enter M as Men or W as women");
        gender = keyboard.nextLine();

        if (gender.equalsIgnoreCase("M"))
        {
            System.out.println("Your BMR value is: ");
        }
        else if (gender.equalsIgnoreCase("W"))
        {
            System.out.println("Your BMR Value is: ");
        }
        else
        {
            System.out.println();
        }

    }

    //Print to the user the amount of chocolate bars they need to consume to maintain their weight

}

1 个答案:

答案 0 :(得分:2)

好吧,我从来没有真正使用过Java,所以如果我犯了任何编码错误,请原谅我......

if (gender.equalsIgnoreCase("M"))
{
    System.out.print("Your BMR value is: "); //Prints without a newline I assume
    System.out.print((66 + (13.8 * (weight * 0.454)) + (5 * (height * 2.54)) - (6.8 * age));
}
else if (gender.equalsIgnoreCase("W"))
{
    System.out.print("Your BMR value is: "); //Prints without a newline I assume
    System.out.print((655 + (9.6 * (weight * 0.454)) + (1.8 * (height * 2.54)) - (4.7 * age));
}
else
{
    System.out.println();
}

好吧,问题是keyboard.nextLine()正在向末尾添加\ n。两种解决方法:

if (gender.equalsIgnoreCase("M\n"))
{
}
else if (gender.equalsIgnoreCase("W\n"))
{
}

OR

if (gender.contains("m") || gender.contains("M"))
{
}
else if (gender.contains("w") || gender.contains("W"))
{
}