用户输入导致输出错误的If-Statement分支

时间:2017-03-19 02:22:49

标签: java if-statement switch-statement

对于我的程序,我试图创建一个公共静态String方法,它接受一个整数和一个字符串,并根据用户输入的月份输出一个字符串。当我编译我的代码并运行程序时,当我输入除“二月”之外的任何月份时,控制台正确输出正确的字符串消息。但是当我为month_name输入“February”时,程序错误地继续第一个if条件并输出嵌入在第一个if条件中的开关的默认条件。它不应该继续执行else条件,因为month_name等于“二月”吗?

我已经查看了代码,并想知道是否因为我没有用括号正确关闭方法,或者我没有在任何语句的末尾放置一个分号但是那不是案件。我检查确保一切拼写正确。我检查确保我输入正确的字符串值,但我无法弄清楚发生了什么。

import java.util.Scanner;  
public class DaysInMonth { 

   public static String daysInaMonth (int year_number, String month_name) {
      if(month_name != "February") {
         switch(month_name) {
            case "January":
            case "March":
            case "May":
            case "July":
            case "August":
            case "October":
            case "December":
              return "There are 31 days in " + month_name + " " + year_number;
            case "April":
            case "June":
            case "September":
            case "November":
                return "There are 30 days in " + month_name + " " + year_number;
            default:
                return "Please input month";
         }  
      }

      else {
         if(year_number % 4 == 0) {
            return "There are 29 days in February " + year_number;
         }
         else {
            return "There are 28 days in February " + year_number;
         }

      }

   }

   public static void main(String[] args) {
   Scanner scnr = new Scanner(System.in);
   String month = " ";
   int year = 0;

   year = scnr.nextInt();

   month = scnr.next();

   System.out.print(daysInaMonth(year, month));


   }


}

1 个答案:

答案 0 :(得分:2)

在java中,您无法使用逻辑运算符(==,!=等)来比较字符串。这样做会比较字符串引用(而不是值)。

这样做......

if (!month_name.equals("February")) {

}