Skip to content

Instantly share code, notes, and snippets.

@LordNairu
Last active December 26, 2015 15:19
Show Gist options
  • Save LordNairu/7172328 to your computer and use it in GitHub Desktop.
Save LordNairu/7172328 to your computer and use it in GitHub Desktop.
Leap year calculator.
package uk.ac.qub.practicals;
// importing scanner
import java.util.Scanner;
public class LeapYearApp {
public final static int CURRENT_YEAR = 2013;
public final static int MINIMUM_YEAR = 1900;
/**
*
*author Niall Collins
*A Java method which gets a year of birth from a user.
*The method checks the int is within the expected range.
*The method then outputs to screen every year between that year and the current year.
*Then the program asks if the user wishes to try again.
**/
// Method for calculating leap years based on
public static void main(String[] args) {
// Variable declaration
int userInput;
int userChoice;
userInput = 0;
userChoice = 0;
// Declaring scanner
Scanner scanner = new Scanner(System.in);
// Quitting check
boolean invalidEntry = false;
// Loop to allow the user the play again
do {
// Loop to prevent the user proceeding with an invalid number
do {
System.out.printf("Please enter the year you were born (%s to %s):
+", MINIMUM_YEAR, CURRENT_YEAR);
userInput = scanner.nextInt();
} while ((userInput < MINIMUM_YEAR) || (userInput > CURRENT_YEAR));
// for loop printing to screen the given year to the current year
for (int loop = userInput; loop <= CURRENT_YEAR; loop++){
if (loop % 4 == 0){
System.out.println(+loop+" (leap year)");
}else {
System.out.println(+loop+"");
}
}
// Checking if user wishes to quit or play again. Looping for unrecognised numbers
do {
System.out.println("\nWould you like to play again?\n0. No\n1. Yes\n");
userChoice = scanner.nextInt();
if ((userChoice == 1) || (userChoice == 0)){
invalidEntry = false;
} else {
System.out.println("Sorry, invalid entry.");
invalidEntry = true;
}
} while (invalidEntry);
// Checking if the user wishes to quit
} while ((userChoice != 0));
System.out.println("Program exiting...");
System.exit(0);
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment