VanDal
VanDal

Reputation: 25

Java: Verify int and range

As part of my class assignment, I have created the following class. The package has 6 classes (Address, Date, Employee, HireDate, Name, and Main). The program runs fine, but I am hung up on one requirement: "All fields are required to be non-blank. The Date fields should be reasonably valid values (ex. month 1-12, day 1-31, year > 1900 and < 2020). Issue appropriate error messages when incorrect data is entered."

I've inserted a do-while loop and if statement to ensure the user puts in an int, but I don't now how to make sure the numbers entered are in a range. I have experimented with try-catch, but can't make it work.

Any help would be greatly appreciated!

From 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("---------------------------------------------");
       }
   }

}

Upvotes: 0

Views: 105

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 338386

Ask for year first. Compare to today’s date via the LocalDate class.

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
}

Then prompt for month.

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

With year and month in hand you can determine the maximum number of days. The YearMonth class provides that feature.

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

Tip: Avoid the troublesome and confusing old date-time classes. They are now legacy, supplanted by the java.time classes.

Upvotes: 1

Susannah Potts
Susannah Potts

Reputation: 827

It's a pretty straightforward solution, just check what the values are:

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.");
    }
}

This should work.

Upvotes: 1

Related Questions