Monday, October 5, 2009

Program to Average an Indefinite List of Integers


Problem: "Write a program called AverageList that reads in a list of integers representing exam scores, and then prints out the average. Because some unprepared student might actually get a score of 0, your program should use -1 as the sentinel to mark the end of the input." (Roberts Ch 4, Exercise 5.)

Program in Eclipse Editor (click to enlarge):


What the output looks like:




What made it tough: One of the earlier problems in this set asked "Write a program that finds the average of a pre-defined list of integers". That was easier, because if the list took in N inputs from the user, you'd know to divide the sum of your integers by N. Another problem asked, "Write a program that finds the sum of an indefinite list of integers." That was also easier, because you could keep adding to your sum until the user entered the sentinel. This one took me a while to figure out how you'd know what to divide your sum by, but it eventually cemented in my head the ways you can use increment operators like i++.

Time to completion: 3 hrs

Lingering Questions: Although my program says that it can average non-negative integers, you really can average any integer except the one used as the sentinel. Ben wants to know why you can't just use a letter as your sentinel, so that you could average any possible integer. I tried setting the sentinel constant as "A." Eclipse didn't like that. Is there a way to design this program so that you could use a letter as your sentinel?


1 comment:

  1. There are a few ways to do what you want, but they all essentially require that you either have a) some way of explicitly checking whether or not the input value is an integer, b) some way of checking whether or not the input value is the (NON-integer) sentinel, and c) some way to ensure the program doesn't try to do something that will make itself explode.

    As a hint for b), you may want to use readLine instead of readInt to interpret the input value as a String and then compare to the sentinel (which should also be declared as a String instead of int to allow for this comparison). If the value equals the sentinel, then break the loop, else.. else what?

    Well, you now have some input String that you know isn't the sentinel. You still need to somehow convert that String to an int so you can use it in your math -- that is, if it can even be interpreted as an integer!

    This is the part that requires new knowledge, which will probably soon be taught to you. For a hint, feel free to look up the Integer.parseInt(String) method, which allows you to explicitly convert a String into an int. To use this effectively you will also need to know a little bit about Exceptions. Together, you will be able to address both a) and c) above and get the program to do exactly what you want!

    Hope this helps. :]

    ReplyDelete