本帖最后由 jwx555 于 2014-7-11 20:12 编辑
如了个题,想做一个输入年份就打印当年2月的天数这样的一个小程序
代码如下:- import java.io.* ;
- import java.util.*;
- class Input
- {
- public static void main(String[] args) throws IOException{
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;
- StringBuilder strBuilder = new StringBuilder() ;
-
- int ch = 0 ;
- while (true)
- {
- ch = br.read() ;
- if (ch == '\r')
- {
- continue ;
- }
- if (ch == '\n')
- {
- String s = strBuilder.toString() ;
- if ("exit".equals(s))
- {
- break ;
- }
- int year = Integer.parseInt(s) ;
- showDays(year) ;
- strBuilder.delete(0,strBuilder.length()) ;
- }else
- strBuilder.append((char)ch) ;
- }
- }
- private static void showDays(int year) {
- Calendar c=Calendar.getInstance();
- c.set(year, 2, 1);
- c.add(Calendar.DAY_OF_MONTH, -1);
- int days=c.get(Calendar.DAY_OF_MONTH);
- System.out.println(days);
- }
- }
复制代码
如果只输入数字没问题,但是输入其他字符会报错- Exception in thread "main" java.lang.NumberFormatException: For input string: "o
- ver"
- at java.lang.NumberFormatException.forInputString(Unknown Source)
- at java.lang.Integer.parseInt(Unknown Source)
- at java.lang.Integer.parseInt(Unknown Source)
- at Input.main(Input.java:26)
复制代码
我希望程序能更健壮些,求解决办法
|