CS230

 

To Vote or not to Vote

Solutions

Voting.java

The problem

You are asked to write a program to decide whether a user is eligible for voting, based on their age (i.e., other factors are not considered here).

Assume that users who have turned 18 years old by November of the current year are considered eligible for voting. It is ok for now if you "hard-wire" (assume) the value for the current year:

int currentYear = 2023; //hard-wire the value for the current year

Also, assume that your program has access to the user's birthday.

Step 1: testing cases

In this problem, start with producing the testing cases first. Yes, some times we do that: we come up with a testing plan before even we start thinking about how to solve the problem, let alone writing any code! This work will give us insight about which steps we need to take to solve the problem, i.e., coming up with an algorithm.

Think carefully: Which testing cases will you choose to test your program on?

Step2: pseudocode and running by hand

Pseudocode is a great tool, if used appropriately. Make sure to always start solving a problem by writing out your plan carefully in pseudocode first. Writing is thinking. This way, once you get to coding, the only thing left to do is translate the carefully written pseudocode in the correct syntax (which is an easier part of programming).

Start on your notebook. Using pseudocode (a mix of English and a computer programming language) write a plan (algorithm) to outline the steps towards a solution to this problem.

Make sure you verify your plan is correct by "running it by hand" on the inputs you decided in the previous step. For each testing case, predict the result your plan should produce. Then, "walk" through your code, step by step, to see what answer it will produce be for each testing case.

Do the two agree?

Step3: write the Java code

At this point you should be able to write your code in BlueJ, compile and run it. Name your class Voting, and save it in a file named Voting.java. Run the program on each testing case. Do you get the correct/expected results?