import java.util.Scanner; /** * Voting class: * Ask the user for their first, last name, their year of birth, and if needed their birth month. * Determines their voting eligibility, and produces a relevant message. * Citizens who have turned 18 in November of this year are considered eligible for voting. * * Goals: * practice with the Scanner class, Strings, boolean expressions, conditionals * * @author Stella K. * @version Aug 13, 2019 * * These is a set of good and comprehensive test cases: * birth year: 2000 - clearly eligible for voting, no birth month is needed * birth year: 2020 - clearly non-eligible for Voting, no birth month is needed * birth year: 2005 - age is exactly 18, so we also need the month: birth month: 11 (Nov) ==> eligible * birth year: 2005 - age is exactly 18, so we also need the month: birth month: 10 (Oct) ==> non-eligible * */ public class Voting { public static void main(String[] args) { //declaration and initializations of vars Scanner scan = new Scanner(System.in); int currentYear = 2023; int birthYear; int age; int birthMonth = 10; //ask user for their first and last name (doing some extras here) System.out.println("What is your first name?"); String firstName = scan.nextLine(); System.out.println("What is your last name?"); String lastName = scan.nextLine(); //ask user for their birth year System.out.println("What is your birth year (2000)?"); birthYear = scan.nextInt(); //use 2000 2020 2005 scan.nextLine(); //flush the scanner //determine user's age age = currentYear - birthYear; //alternatively use the following expression to avoid hardwiring of the current year //java.time.Year.now().getValue() //instead of 2023 //ask user for their birth month, but only if their age is 18 if (age == 18) { System.out.println("What is your birth month (1-12)?"); birthMonth = scan.nextInt(); } //determine voting eligibility boolean canVote = true; if ((age < 18) || (age == 18 && (birthMonth == 12))) { canVote = false; } //present a suitable message if (!canVote) { System.out.println("Too young to vote. Check again next year!"); } else { //if eligible to vote, ask whether they are registered System.out.println("You are eligible to vote. Have you already registered? (y/n)"); String registered = scan.nextLine(); if (registered.equalsIgnoreCase("y")) { System.out.println("Good for you, " + firstName + " " + lastName + "!"); } else { System.out.println("You should register soon, " + firstName + " " + lastName + "!"); } } scan.close(); System.out.println("Bye now."); } }