- Java code
import java.util.Scanner;public class Year{ public static void main(String[] args) { int year; Scanner scan = new Scanner(System.in); System.out.println("请输入年份:"); year = scan.nextInt(); /*if (year < 0 || year > 3000) { System.out.println("输入有误,请重新输入:"); year = scan.nextInt(); }*/ testYear(year); if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) { System.out.println(year + "是闰年!"); } else { System.out.println(year + "不是闰年!"); } } static int testYear() { //此处要用static Scanner scan = new Scanner(System.in); if(scan.hasnextInt()) return scan.nextInt(); else { System.out.println("输入有误,请重新输入:"); return testYear(); } }}
我想知道这个程序怎么改才能实现如果0--3000之内的数就输出:有误,请重新输入。并且能够重新输入,直到输入的是0--3000内的整数。。。大神请解决
------解决方案--------------------------------------------------------
- Java code
public static void main(String[] args) { int year; boolean flag = true; System.out.println("==========请输入年份============"); while(flag){ try{ Scanner scanner = new Scanner(System.in); year = scanner.nextInt(); if(year > 0 && year <3000){ if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){ System.out.println(year+"是闰年"); }else{ System.out.println(year + "是平年 "); } flag = false; }else{ System.out.println("输入的数字不在0-3000范围,请重新输入"); } }catch(Exception e){ System.out.println("========输入的年份不是整数,请重新输入==========="); } } }
------解决方案--------------------------------------------------------
只是给你重写一下那个函数:
static int testYear() {
Scanner scan = new Scanner(System.in);
int year = 0;
while(true){
try{
year = scan.nextInt();
if(year>1 && year<3000)
break;
System.out.println("输入的数字不再1到3000之间,重新输入");
}catch{
System.out.println("输入的不是数字,重新输入");
}
}
}
------解决方案--------------------------------------------------------
来个
while(true){
if(year<0|year>3000){
System.out.print("重新输入");
continue;
}
......
}