Je travaille sur un atelier pour mon JAVA. Il y a une partie que je vais avoir du mal à comprendre: Appliquer les formules suivantes basées sur le genre (doit utiliser une instruction if (s)): Hmale_child = ((Hmother * 13/12) + Hfather)/2 OU Hfemale_child = ((Hfather * 12/13) + Hmother)/2Utilisation de la déclaration If avec des formules JAVA
Comment utiliser une instruction if avec ces formules? J'utilise le Hmale_child si l'utilisateur saisit que le genre de son enfant est masculin. Mais toutes les déclarations if que j'ai vues ont à voir avec les nombres. Est-ce que quelqu'un peut-il me montrer la bonne direction?
Quelque chose comme: si (genre == mâle) ??
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;
}
}
}
Pour comparer les chaînes, vous n'utilisez généralement pas '=='. Au lieu de cela, vous voulez probablement écrire 'if (gender.equals (" M "))' ou 'if (gender.equalsIgnoreCase (" M "))' ou quelque chose de similaire. Pour plus d'informations sur pourquoi, regardez les réponses à [cette question] (http://stackoverflow.com/q/513832/) –
Quand je fais ceci, j'obtiens immédiatement l'erreur, "ne trouve pas le symbole". Cela signifie que je dois déclarer et initialiser la variable, non? Donc j'ai défini gender.equals, Hmother, et Hfather comme Strings? –
Oups, désolé, vous l'avez appelé 'input', pas' gender'. Donc, 'if (input.equals (" M "))'. –