在java中使用char的条件

时间:2013-11-28 04:57:49

标签: java

只是想知道如何打印它。如果用户输入条件正确?试图让它打印出来以显示结果

if(SkillLevel > 1) {
        System.out.println("Would you like to sign up for medical y/n?");
        Medical = sc.next().charAt(0);
        if (Medical == 'y') {
            TotalPay = TotalPay -  23.50;
        }

       if(Medical == "y") {
           System.out.println("\nMedical Insurance cost : -$23.50");    
       }

}

3 个答案:

答案 0 :(得分:1)

您根本不需要内部if

if (Medical == 'y') { // Checks if the char Medical is 'y' or not
    TotalPay = TotalPay -  23.50; 
    // if(Medical == "y") {  // this line is not required.
    System.out.println("\nMedical Insurance cost : -$23.50");   
}

虽然您应该注意到内部if正在尝试将LHS上的字符与RHS上的字符串进行比较。此外,==用于对象引用比较(在非基本类型的情况下),并且必须使用equals()方法进行字符串值相等性检查。

答案 1 :(得分:0)

如果您只想在下面输入字符y就足够了,

if (Medical == 'y') { // Checks if the char Medical is 'y' or not
    TotalPay = TotalPay -  23.50; 
    System.out.println("\nMedical Insurance cost : -$23.50");   
}

但是,如果用户输入Y而不是y,则验证将为false,希望您不要将其视为错误。然后你可以使用 -

if (Medical == 'y' || Medical == 'Y') {//Checks if the char Medical is 'y' or not
    TotalPay = TotalPay -  23.50; 
    System.out.println("\nMedical Insurance cost : -$23.50");   
}

但最好使用String#equals()String#equalsIgnoreCase()

if (Medical.equalsIgnoreCase("y")) { // Checks if the char Medical is 'y' or not
    TotalPay = TotalPay -  23.50; 
    System.out.println("\nMedical Insurance cost : -$23.50");   
}

答案 2 :(得分:0)

如果第一个char'y',则显示和计算都会发生,那么您只需要第一个if语句。

不仅如此,您的第二个if语句永远不会成立,因为类型不兼容(Stringchar)。它甚至不应该让你编译。

这就是你需要的:

if (SkillLevel > 1) {
    System.out.println("Would you like to sign up for medical y/n?");
    Medical = sc.next().charAt(0); // make sure you define Medical as char
    if (Medical == 'y') {
        TotalPay = TotalPay - 23.50;
        System.out.println("\nMedical Insurance cost: -$23.50");
    }
}