Java性别char无效



我正在尝试测试性别char是否无效,如果是,则打印一条错误消息,解释输入要求然后结束程序。如果性别有效(MFmf)继续执行程序。我还需要在性别变量上使用开关语句来确定要使用的公式。我的印刷显示应读:

孩子的成人身高为5.58。

应使用printf()和2个小数位置显示高度。

这是我到目前为止无法正确计算的内容。

import java.util.Scanner;
public class Workshop3GenderModification {
public static void main(String[] args) {
// TODO Auto-generated method stub
int gender;
gender = 'M';
gender = 'F';
double cheight=0;
Scanner input = new Scanner(System.in);
//father height
System.out.print("Enter your father height in feet ");
int ffeet=input.nextInt();
System.out.print("Enter father height in inches ");
int finches=input.nextInt();
//mother height
System.out.print("Enter mother height in feet ");
int mfeet=input.nextInt();
System.out.print("Enter mother height in inches ");
int minches=input.nextInt();
int mheight = mfeet * 12 + minches;
int fheight = ffeet * 12 + finches;
// child gender
System.out.print("Enter M for male or F for female ");
gender = input.next().charAt (0);
// male or female
input.nextLine();
switch (gender){
  case 'M':
  cheight =(int)((fheight * 13/12.0)+ mheight)/2;
  break;
}
switch (gender){
  case 'F' :
  cheight =(int)((mheight * 12/13.0) + fheight)/2 ;
  break;
}
int cfeet= (int)cheight/12;
int cinched= (int)cheight%12;
double aheight=(cfeet/cinched);
System.out.print(cfeet +"'" + cinched + """);
System.out.printf("will be the adult child's height" +"%.2f", aheight);
   }
}

您的已发布的代码有两个开关语句。您可能想要一个:

switch (gender){
  case 'M':
    cheight =(int)((fheight * 13/12.0)+ mheight)/2;
    break;
  case 'F' :
    cheight =(int)((mheight * 12/13.0) + fheight)/2 ;
    break;
}

如果要处理无效输入的问题,则可以使用默认情况进行此操作:

switch (gender){
  case 'M':
    cheight =(int)((fheight * 13/12.0)+ mheight)/2;
    break;
  case 'F' :
    cheight =(int)((mheight * 12/13.0) + fheight)/2 ;
    break;
  default:
    invalidInput = true; // you'll want to declare this above and 
                         // initialize it to false
}

现在,您可以检查是否已将InvalidInput设置为True,如果是的,则适当响应。

您有两个开关语句,没有默认的开关情况。如果您只希望性别与" M"," M'"," F"," F"一起工作,那么请让案例陷入相似的角色,即。M-M和F-F。

switch(gender) {
    case 'M':
    case 'm':
        cheight =(int)((fheight * 13/12.0)+ mheight)/2;
        break;
    case 'F':
    case 'f':
        cheight =(int)((mheight * 12/13.0) + fheight)/2;
        break;
    default:
        System.exit(0);   // stop process
        break;
}
// if a F, f, M, or m were not entered, this will never be reached
NumberFormat nm = new DecimalFormat("#0.00");
System.out.println( "output: " + nm.format(cheight) );

最新更新