Monday, March 2, 2015

Age checker

Tim and I made a java program that checks to see if you're 18 years old or older.

import javax.swing.JOptionPane;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class home {
public static void main(String[] args) {
int day = 0;
int month = 0;
int year = 0;
boolean workingstr = false;
while (workingstr == false) {
String inputValue = JOptionPane.showInputDialog("Please type in your birthday (mm/dd/yy)");
workingstr=true;
try {
day = Integer.parseInt(inputValue.substring(4,5));
month = Integer.parseInt(inputValue.substring(0,2));
year = Integer.parseInt("19"+inputValue.substring(inputValue.length()-2,inputValue.length()));
} catch (NumberFormatException e) {
workingstr=false;
} catch (StringIndexOutOfBoundsException e) {  
workingstr=false; //This section of the program will repeat if any errors are thrown trying to convert the
}                                      //input string to integers.
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar cd = Calendar.getInstance();
int todayDay = Integer.parseInt(dateFormat.format(cd.getTime()).substring(0,2));
int todayMonth = Integer.parseInt(dateFormat.format(cd.getTime()).substring(4,5));
int todayYear = Integer.parseInt(dateFormat.format(cd.getTime()).substring(6,10));

if (day<=todayDay) {
month++;
}
if (month<=todayMonth){
year++;
}
if (year+18<=todayYear) {
System.out.println("You're good.");
} else {
System.out.println("Nope! You're underage.");
}
}
}

No comments:

Post a Comment