java编程,输入月份判断季节

程序如下
import java.io.*;
class Season{
public static void main(String args[])
throws IOException{
int month;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入月份:");

month=br.read();
String season;
if(month==12||month==1||month==2)
season="冬天";
else if(month==3||month==4||month==5)
season="春天";
else if(month==6||month==7||month==8)
season="夏天";
else if(month==9||month==10||month==11)
season="秋天";
else season="不存在的月份";
System.out.println(month+"月份是"+season);
}
}

问题是输入月份:1
之后,显示的是:49月份是不存在的月份

代码喝注释如下:

public static void main(String[] args) {  System.out.print("Please input the month to check:");  int month = new Scanner(System.in).nextInt();//月份//月份不在1~12的情况,提醒输入错误  if (month <= 0 || month > 12) {   System.out.println("Error! month must be between 1 and 12!");  } 
//1-3月是春天
else if (month <= 3) {   System.out.println("Month " + month + " is in Spring!");  } 
//4-6月是夏天
else if (month <= 6) {   System.out.println("Month " + month + " is in Summer!");  } 
//7-9月是秋天
else if (month <= 9) {   System.out.println("Month " + month + " is in Autumn!");  } 
//10-12月是冬天
else {   System.out.println("Month " + month + " is in Winter!");  } }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-22
BufferedReader的read()方法读的是一个字符,你用int的变量去接收得到的是49啊,char型的1值等于int的49
month = br.read();
改为:month = br.read() - '0'; 或者 string s = br.readLine(); month = Integer.parseInt(s);
试试吧^_^
不过第一种该法你输入两位数的话,还是不对;还是第二种方法好些。
第2个回答  推荐于2017-09-03
import java.io.*;

public class Season {
public static void main(String args[]) throws IOException {
String month;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入月份:");

month = br.readLine();
String season;
if (month.equals("12") || month.equals("1") || month.equals("2"))
season = "冬天";
else if (month.equals("3") || month.equals("4") ||month.equals("5"))
season = "春天";
else if (month.equals("6")|| month.equals("7") || month.equals("8"))
season = "夏天";
else if (month.equals("9") || month.equals("10") ||month.equals("11"))
season = "秋天";
else
season = "不存在的月份";
System.out.println(month + "月份是" + season);
}
}追问

感谢,该程序是正确的,
弱弱地问一句
为什么要用 这个 if (month.equals("12") || month.equals("1") || month.equals("2"))
season = "冬天";
而 用这个 if(month==12||month==1||month==2)
season="冬天";是错的?

追答

字符串间的比较用equals()

本回答被提问者采纳
第3个回答  2011-03-22
你从system.in中read出来的是字符型的1,他的ascii编码,或者说是数值编码为0x31,即49。
如果你要使用int型变量判断,在判断以前减48,这样就对了。
第4个回答  2011-03-22
你输入其它月份,也会显示不存在。
month=br.read(); 这样直接赋值不对。