有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ifelse语句不在Java中执行

为什么我的if-else语句在gender == "m"gender == "f"时不执行

Scanner input = new Scanner(System.in);


    do 
    {
        System.out.print("Please enter 'm' for male and 'f' for female child: ");
        String gender = input.next();

        System.out.print("The height of the mother in inches: ");
        int motherHeight = input.nextInt();

        System.out.println("The height of the father in inches: ");
        int fatherHeight = input.nextInt();

        if(gender == "m") 
        {
            double childHeight = ((motherHeight * 13/12) + fatherHeight) / 2;
            System.out.println(childHeight);
        }
        else if (gender == "f")
        {
            double childHeight = ((fatherHeight * 13/14) + motherHeight) / 2;
            System.out.println(childHeight);
        }


    }

    while(input.hasNext());

共 (1) 个答案

  1. # 1 楼答案

    使用正确的方法比较字符串,因为您正在比较字符串的内存位置

    问题

    if(gender == "m") //compares memory location of the String will return always false
    

    解决方案

    if(gender.equals("m"))