Book club points

The problem

Serendipity Booksellers has a book club that awards points to its customers based on the number of books purchased each month. The points are awarded as follows:

  • If a customer purchases 0 books, he or she earns 0 points.
  • If a customer purchases 1 book, he or she earns 5 points.
  • If a customer purchases 2 books, he or she earns 15 points.
  • If a customer purchases 3 books, he or she earns 30 points.
  • If a customer purchases 4 or more books, he or she earns 60 points.

Write a program that asks the user to enter the number of books that he or she has purchased this month and displays the number of points awarded.

Breaking it down

public static void main(String[] args) {

    // Define variables
    int numberOfBooksPurchased;
    int pointsAwarded;

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Get the number of books purchased this month.
    System.out.print("How many books have you purchased? ");
    numberOfBooksPurchased = keyboard.nextInt();
    
    keyboard.close();

    // Determine the number of points to award.
    pointsAwarded = getPointsEarned(numberOfBooksPurchased);

    // Display the points earned.
    System.out.println("You've earned " + pointsAwarded + " points.");
}

/**
 * Method should return the number of points earned based on the number of
 * books purchased
 * 
 * @param numberOfBooksPurchased
 * @return points earied
 */
public static int getPointsEarned(int numberOfBooksPurchased) {

    if (numberOfBooksPurchased < 1) {
        return 0;
    } else if (numberOfBooksPurchased == 1) {
        return 5;
    } else if (numberOfBooksPurchased == 2) {
        return 15;
    } else if (numberOfBooksPurchased == 3) {
        return 30;
    } else {
        return 60;
    }
}

Output

How many books have you purchased? 2
You have earned 15 points.

Unit tests

@Test
public void test_getPointsEarned_0() {
    
    int points = BookClubPoints.getPointsEarned(0);
    
    assertEquals(0, points);
}

@Test
public void test_getPointsEarned_1() {
    
    int points = BookClubPoints.getPointsEarned(1);
    
    assertEquals(5, points);
}

@Test
public void test_getPointsEarned_2() {
    
    int points = BookClubPoints.getPointsEarned(2);
    
    assertEquals(15, points);
}

@Test
public void test_getPointsEarned_3() {
    
    int points = BookClubPoints.getPointsEarned(3);
    
    assertEquals(30, points);
}

@Test
public void test_getPointsEarned_4() {
    
    int points = BookClubPoints.getPointsEarned(4);
    
    assertEquals(60, points);
}

Level Up

  • Enhance the program to allow the user to enter in N months which will keep a summary of all the points earned.
  • Enhance the program to keep track of a specified month and points displaying in a pretty matrix.
  • Enhance the program to summarize points earned by quarter using java 8.