eclipse中排除非法情况

怎么样做到当用户输入1~12月份以外的数字时,提示用户输入错误,重新输入?

package task;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args){
System.out.println("Please input one month:");
Scanner m = new Scanner(System.in);
int Month=m.nextInt();
switch(Month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:System.out.println(Month+"月的天数为:"+31);break;
case 4:
case 6:
case 9:
case 11:System.out.println(Month+"月的天数为:"+30);break;
default:System.out.println(Month+"月的天数为:"+29);break;
}
}
}

case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:System.out.println(Month+"月的天数为:"+31);break;
case 4:
case 6:
case 9:
case 11:System.out.println(Month+"月的天数为:"+30);break;
case 2:System.out.println(Month+"月的天数为:"+29);break;
default:System.out.println("输入错误,重新输入");break;

首先,你应该规定输出什么数值是整个函数操作结束;其次,在while循环中进行输入判断并设置操作结束条件,例如-1结束操作;非1-12,则继续下一轮循环。最后,其实月份就是两个分支,没有必要用这么多switch的,直接用if就可以了。修正代码如下:

 public static void main(String[] args){
        System.out.println("Please input one month:1-12的数值;输入-1,结束操作。");
        Scanner m = new Scanner(System.in);
        while(true){
            int Month=m.nextInt();
            if(Month==-1){
                m.close();
                break;
            }

            if(Month<1||Month>12){
                System.out.println("输入月份错误,请重新输入1-12之间的数字。");
                continue;
            }

            if(Month==2){
                System.out.println(Month+"月份总共有28天");
                continue;
            }

            if(Month==1||Month==3||Month==5||Month==7||Month==8||Month==10||Month==12){
                System.out.println(Month+"月份总共有31天");
                continue;
            }

            System.out.println(Month+"月份总共有30天");
        }
    }