无法比较char

时间:2013-10-14 03:13:55

标签: java

  boolean isGender = gender == "M";

此语句返回错误“无法比拟的类型” 之前的其余代码是

import java.util.Scanner;
public class BMR
{
  public static void main(String[] args)
  {
  //Scanner
  Scanner in = new Scanner(System.in);

  //Get info
  System.out.println("Enter your name: ");
  String name = in.nextLine();
  System.out.println("Gender (M or F): ");
  String genderString = in.next();
  char gender = genderString.charAt(0);
  System.out.println("Enter your age: ");
  int age = in.nextInt();
  System.out.println("Height in inches: ");
  int height = in.nextInt();
  System.out.println("Weight in pounds: ");
  int weight = in.nextInt();
  System.out.println();

  //calculate BMR
  boolean isGender = gender == "M";

不知道为什么这不起作用

2 个答案:

答案 0 :(得分:5)

"M"不是字符,而是String

根据您的代码,您应该使用gender == 'M'

作为旁注,如果genderString,您应该使用gender.equals("M"),或者如果不关心此案例,则可以使用gender.equalsIgnoreCase("M")代替

答案 1 :(得分:0)