gpt4 book ai didi

java - 在 JAVA 公式中使用 If 语句

转载 作者:行者123 更新时间:2023-11-30 10:37:59 25 4
gpt4 key购买 nike

我正在为我的 JAVA 开发一个研讨会。有一部分我很难理解:根据性别应用以下公式(必须使用 if 语句):Hmale_child = ((Hmother * 13/12) + Hfather)/2 或者Hfemale_child = ((Hfather * 12/13) + Hmother)/2

如何对这些公式使用 if 语句?如果用户输入他们 child 的性别是男性,我会使用 Hmale_child。但我见过的所有 if 语句都与数字有关。谁能指出我正确的方向?

类似于:if (gender == male) ??


import java.util.Scanner;

public class WKSP6Trial
{
public static void main(String[] args)
{
Scanner scannerObject = new Scanner(System.in);

Scanner inp = new Scanner(System.in);
String Letter;
String input = "";
String exit = "exit";
boolean isStringLetter = true;
System.out.println("Welcome! If at any time you wish to exit the program, type the word exit, and press enter.");

while(true)
{
System.out.println("\nPlease enter letters m or f only as you enter your child's gender: ");
input = inp.nextLine();

if(input.equalsIgnoreCase(exit)){break;}
isStringLetter = input.matches("[m/f/M/F]+");
if(isStringLetter == false)
{
System.out.println("\nYou entered a non letter " + input);
System.out.println("Remove all non letters aside from m or f from your input and try again !");
break;
}

System.out.println("You entered the gender of your child.");

System.out.println("Next enter the height of the child's father in feet followed by ");
System.out.println("the father's height in inches: ");

int n1, n2;
n1 = scannerObject.nextInt();
n2 = scannerObject.nextInt();
System.out.println("You entered " + n1 + " followed by " + n2);

System.out.println("Finally, enter the height of the child's mother followed by ");
System.out.println("the mother's height in inches: ");

int d1, d2;
d1 = scannerObject.nextInt();
d2 = scannerObject.nextInt();
System.out.println("You entered " + d1 + " followed by " + d2);

Scanner in = new Scanner(System.in);

System.out.print("Convert from: ");
String fromUnit = in.nextLine();
System.out.print("Convert to: ");
String toUnit = in.nextLine();


//below is what I'm uncertain of
if(gender == m)
Hmale_child = ((Hmother * 13/12) + Hfather)/2;
}
}
}

最佳答案

您可以使用 equalsequalsIgnoreCase检查字符串输入的方法:

if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
else { // alternatively - check if the gender is female, just to be sure
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}

编辑:
如果您绝对不能使用 else block ,则可以将相同的逻辑表示为两个 if 语句,因为性别不能同时是 "m"“f”:

if (gender.equalsIgnoreCase("m")) {
child = ((Hmother * 13.0/12) + Hfather)/2.0;
}

if (gender.equalsIgnoreCase("f")) {
child = ((Hfather * 12.0/13) + Hmother)/2.0;
}

关于java - 在 JAVA 公式中使用 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39925110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com