切换语句反向

时间:2014-03-28 13:31:51

标签: java switch-statement

好的,所以我正在尝试为学校完成这个项目,它要求我做几个月的转换声明。因此,如果用户输入1,它将打印出1月等等...我得到这个错误,它说:找不到符号 - 变量1月

import java.util.*;
/**
 * Outputs the number on a month name entered by the user.
 * 
 * @author Jack
 * @version 1a
 */
public class MonthSwitchReverse {
    public static void main(String[] args) {


        Scanner in = new Scanner (System.in);

        int monthString;
        String month;



        System.out.println(" Jan = 1 / Feb = 2 / March = 3 / April = 4 / MAy = 5 / June = 6");
        System.out.println(" July = 7 / Aug = 8 / Sep = 9 / Oct = 10 / Nov = 11 / Dec = 12");
        System.out.print("Choose a month above and the system will print out the number assigned to that month: ");
        month = in.next();


        switch (month) {
            case "January":  monthString = 1;
                     break;
            case "February":  monthString = 2;
                     break;
            case "March":  monthString = 3;
                     break;
            case "April":  monthString = 4;
                     break;
            case "May":  monthString = 5;
                     break;
            case "June":  monthString = 6;
                     break;
            case "July":  monthString = 7;
                     break;
            case "August":  monthString = 8;
                     break;
            case "September":  monthString = 9;
                     break;
            case "October": monthString = 10;
                     break;
            case "November": monthString = 11;
                     break;
            case "December": monthString = 12;
                     break;
            default: monthString = 404;
                     break;
        }
        System.out.println(monthString);
    }
}
编辑:我修好了。谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

由于您要传递一个整数来切换,因此每种情况都应该是一个int值。

例如

  case 1:  monthString = "1";
  case 2:  monthString = "2";

同样的,保留所有。

建议阅读:Switch in java.