Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

More Tasks

Task 7.7.1

In this task, you will create a program that computes these statistics for a numeric dataset:

  • Minimum
  • Maximum
  • Mean (‘average’)
  • Median

Tip

To implement this quickly and easily, you will need to make effective use of the methods and extension functions of lists. Everything you need for this task was mentioned in the discussion of extension functions on collections.

A good solution to this task shouldn’t require much more than 30 lines of source code (excluding blank lines & comments).

  1. Edit the file named Stats.kt, in the tasks/task7_7_1 subdirectory of your repository.

    In this file, write a function that prompts the user to enter a series of floating-point values, storing them in a list. The function should return the list.

    Kotlin’s buildList() provides an elegant way of implementing this:

    fun readData() = buildList {
        // Print a prompt for the user
    
        // Write a loop to read the numbers
        // Inside this loop, call add() to add a number to list
    }
    

    Your program will need to cope with varying amounts of data, so you should have some way of terminating the input when the user has finished entering values.

  2. Write a second function that computes the median of a list of floating-point values.

  3. Write a third function that displays the required statistics for a list of floating-point values. Obviously, this should make use of the function you created in the previous step. The other statistics can each be computed using a single line of code.

  4. Finally, write a two-line main() function that uses the previously written functions to read the data and display the required statistics.

Task 7.7.2

Edit the file named Contacts.kt, in the tasks/task7_7_2 subdirectory of your repository.

In this file, write a Kotlin program to simulate a database of contacts and their telephone numbers. Use a map of strings onto strings to represent this database.

Your program should repeatedly prompt the user to enter a contact’s name. If the name is present in the map, the program should display the corresponding phone number; otherwise, it should prompt for entry of that person’s phone number and then store the pairing of name and number in the map.