The problem
Write a program that calculates the amount a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should display a table showing the salary for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked
Breaking it down
public static void main(String[] args) {
int maxDays; // number of days
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the number of days.
System.out.print("Days of work? ");
maxDays = keyboard.nextInt();
// Validate the input.
while (maxDays < 1) {
System.out.print("The number of days must be greater than 0.\n"
+ "Re-enter the number of days: ");
maxDays = keyboard.nextInt();
}
// close scanner
keyboard.close();
// Display the report header.
System.out.println("Day\t\tPennies Earned");
// call getPay to calculate total amount of pay
// passing in a start penny of 1 and
// max days entered by user
List<Double> pay = getPay(maxDays, 1);
for (int x = 0; x < pay.size(); x++) {
System.out.println((x + 1) + "\t\t" + pay.get(x));
}
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// calculate totalPay with java 8
double totalPay = pay.stream().mapToDouble(Double::doubleValue).sum();
System.out.println("Total pay: $" + dollar.format(totalPay / 100.0));
}
/**
* The method will calculate the pay period based on parameters passed.
*
* @param numberOfDays
* @param pennies
* @return list of pay period
*/
public static List<Double> getPay(int totalNumberOfDays, int pennies) {
List<Double> pay = new ArrayList<>();
// add first day
pay.add(new Double(1));
int day = 1;
while (day < totalNumberOfDays) {
pay.add(new Double(pennies *= 2));
day++;
}
return pay;
}
Unit tests
@Test
public void getPay_test() {
List<Double> days = PenniesForPay.getPay(5, 1);
assertThat(
days,
contains(new Double(1.0), new Double(2.0), new Double(4.0),
new Double(8.0), new Double(16.0)));
}
Output
Days of work? 10
Day Pennies Earned
1 1.0
2 2.0
3 4.0
4 8.0
5 16.0
6 32.0
7 64.0
8 128.0
9 256.0
10 512.0
Total pay: $10.23
Level Up
- What happens if the number of days provided is greater than the size that the data type can hold? Meaning, double data type is a double-precision 64-bit IEEE 754 floating point, what other data type could you use?