Java:验证int和范围

时间:2016-10-07 20:37:02

标签: java

作为课程作业的一部分,我创建了以下课程。该软件包有6个类(Address,Date,Employee,HireDate,Name和Main)。该程序运行正常,但我挂了一个要求:“所有字段都必须是非空白。日期字段应该是合理有效的值(例如,第1-12个月,第1-31天,年份> 1900和< 2020)。输入错误数据时发出相应的错误消息。“

我插入了一个do-while循环和if语句以确保用户放入一个int,但我现在不知道如何确保输入的数字在一个范围内。我已尝试过try-catch,但无法使其正常工作。

非常感谢任何帮助!

来自Main:

public class A1 
{

    public static void main(String[] args) 
    {
       Scanner scan = new Scanner(System.in);

       int n = 0;
       int day = 1;
       int range = 0;
       int minDay = 1;
       int highDay = 31;
       boolean isNumber;
       boolean validDay;
       boolean inputValidate;

       do 
       {
        System.out.println("How many Employees are you adding today?: ");
            if (scan.hasNextInt()) 
            {
                n = scan.nextInt();
                isNumber = true;

            }
            else
            { 
                System.out.println("You must enter integers. Please try again.\n" ); 
                isNumber = false;
                scan.next();
            }
        } 
        while (!(isNumber));


       Employee employees[] = new Employee[n];

       for(int i=0; i<employees.length; i++){
           Employee emp = new Employee();
           Address address = new Address();
           Name name = new Name();
           Date date = new Date();
           System.out.println("Enter Employee Number :");
           int empNo = scan.nextInt();

           emp.setEmpNo(empNo);

           System.out.println("Enter Employee First Name :");
           String firstName = scan.next();
           System.out.println("Enter Employee Last Name :");
           String lastName = scan.next();
           name.setFirstName(firstName);
           name.setLastName(lastName);

           emp.setName(name);

           System.out.println("Enter City :");
           String city = scan.next();

           System.out.println("Enter State :");
           String state = scan.next();

           System.out.println("Enter street :");
           String street = scan.next();
           System.out.println("Enter Zip Code :");
           int zipCode = scan.nextInt();          

           address.setCity(city);
           address.setState(state);
           address.setStreet(street);
           address.setZipCode(zipCode);


           do 
       {
        System.out.println("Day of Hire: ");
            if (scan.hasNextInt()) 
            {
                day = scan.nextInt();
                isNumber = true;

            }
            else
            { 
                System.out.println("You must enter integers. Please try again.\n" ); 
                isNumber = false;
                scan.next();
            }
        } 
        while (!(isNumber));

//           System.out.println("Enter Day :");
//           int day = scan.nextInt();          
           System.out.println("Enter Month :");
           int month = scan.nextInt();          
           System.out.println("Enter Year :");
           int year = scan.nextInt();          
           date.setDay(day);
           date.setMonth(month);
           date.setYear(year);
           emp.setDate(date);
           emp.setAddress(address);
           employees[i] = emp;          
       }
       System.out.println("Given Employee Details Are : ");
       System.out.println("-----------------------------------------------");
       for(int i=0; i<employees.length; i++){
           Employee emp = employees[i];
           System.out.println("Given Emp No : "+emp.getEmpNo());
           System.out.println("Given First Name : "+emp.getName().getFirstName());
           System.out.println("Given Last Name : "+emp.getName().getLastName());
           System.out.println("Given Street : "+emp.getAddress().getStreet());
           System.out.println("Given City : "+emp.getAddress().getCity());
           System.out.println("Given State : "+emp.getAddress().getState());
           System.out.println("Given Zip Code : "+emp.getAddress().getZipCode());
           System.out.println("Given Day : "+emp.getDate().getDay());
           System.out.println("Given Month : "+emp.getDate().getMonth());
           System.out.println("Given Year : "+emp.getDate().getYear());
           System.out.println("---------------------------------------------");
       }
   }

}

2 个答案:

答案 0 :(得分:1)

这是一个非常简单的解决方案,只需检查值是什么:

int month, day, year;
List<Integer> shortMonths = Arrays.asList(1,3,5,7,8,10,12);

while((month = scan.nextInt()) < 1 || month > 13) {
    System.out.println("Please enter a valid month...");
}

while((year = scan.nextInt()) < 1900 || year > 2020) {
    System.out.println("Please enter a valid year...");
}

while(true) {
    day = scan.nextInt();
    if(day > 0 && day < 29) { //Must be valid (1-28)
        break;
    } else if(year%4 == 0 && day == 29) { // Could be a leap year making the 29th within common range of all months.
        break;
    } //Only the 29th or 30th could get this far and be valid on a short month
      else if (shortMonths.contains(month) && (day == 30 || day == 29)) { 
        break;
    } else if (day > 0 || day < 32) { //Is it in range on any other month and year?
        break;
    } else { //Nope
        System.out.println("Please enter a valid day.");
    }
}

这应该有用。

答案 1 :(得分:1)

先要求年份。通过LocalDate课程与今天的日期进行比较。

int year = scan.nextInt();
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int thisYear = today.getYear();
if( ( year < 1900 ) || ( year > ( thisYear + 4 ) ) ) {
    … report error to user
}

然后提示月份。

int month = scan.nextInt();
if( ( month < 1 ) || ( month > ( 12 ) ) ) {
    … report error to user
}

随着年份和月份的到来,您可以确定最大天数。 YearMonth类提供了该功能。

YearMonth ym = YearMonth.of( year , month );
int lengthOfMonth = ym.lengthOfMonth();
int dayOfMonth = scan.nextInt();
if( ( dayOfMonth < 1 ) || ( dayOfMonth > ( lengthOfMonth ) ) ) {
    … report error to user
}

提示:避免麻烦和混淆旧的日期时间类。它们现在已经遗留下来,取而代之的是java.time类。