如何将char更改为布尔值?

时间:2014-10-22 09:11:16

标签: java char boolean setter getter

我的问题是如何将char更改为布尔值。例如,我有2个班级

一个是患者类,只有出血史和方法信息:

Public class Patient {

        private static String name;
        private static boolean bleedingHistory = true;
        private String answer;
        private double ureaLevel;
        private double proLevel;


        public Patient()
        {
            String name = "unknown";
            double ureaLevel = 0.0;
            double proLevel = 0.0;
            boolean bleedingHistory = false;

        }

        public Patient (String inName, boolean inBleedingHistory)
        {
            if (name != "" || bleedingHistory == true)
            {
                name = inName;
                bleedingHistory = inBleedingHistory;

            }

            else
            {
                name = "unknown";
                bleedingHistory = false;    
            }

            proLevel = 0.0;
            ureaLevel = 0.0;
        }
    public boolean getBleedingHistory()
            {
                return bleedingHistory;

            }

            public void setBleedingHistory(boolean inBleedingHistory)
            {

                bleedingHistory = inBleedingHistory;
            }

并且另一个班级的一部分呼叫耐心检查,要求用户输入患者是否有出血史:

System.out.print("Does the patient has a history of bleeding(Yes or No)?: ");
        char inBleedingHistory; 
        do 
        {
            inBleedingHistory = sc.next().charAt(0);
            if (inBleedingHistory != 'n' && inBleedingHistory != 'N' && inBleedingHistory != 'y' && inBleedingHistory != 'Y')
            {System.out.println("Invalid answer, please enter YES or NO: ");

            sc.nextLine();
            }

        }while (inBleedingHistory != 'n' && inBleedingHistory != 'N' && inBleedingHistory != 'y' && inBleedingHistory != 'Y');

        pat1 = new Patient (inName, inBleedingHistory);

我知道我的病史检查部分的病史出血是错误的,但我该怎么做才能纠正它?感谢

2 个答案:

答案 0 :(得分:1)

pat1 = new Patient(inName, (inBleedingHistory=='y' || inBleedingHistory=='Y'));

答案 1 :(得分:0)

pat1 = new Patient (inName, Character.toString(inBleedingHistory).equalsIgnoreCase("y"));

如果inBleedingHistory匹配y或Y,则返回true。它还会在比较之前将Char转换为String。

您也可以使用

将其强制转换为String
pat1 = new Patient (inName, String.valueOf(inBleedingHistory).equalsIgnoreCase("y"));

是一样的。

你也可以比较可能是最快的方式。

Character yesLower, yesUpper;

yesLower = new Character('y');
yesUpper = new Character('Y');

pat1 = new Patient (inName, (inBleedingHistory.compareTo(yesLower ) == 0 || inBleedingHistory.compareTo(yesUpper) == 0));