SOURCE CODE FILES FOR Average EXAMPLES ------------------------------------------------------- /** * Project Average1 * Class Main * * Compute the average of integers entered * in an option dialog. The user enters the * count of numbers to enter in advance. */ import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { // number must be initialized to 0 because // the compiler cannot determine whether // the for loop executes at least once. int number = 0, count, sum = 0, i; double average; count = Integer.parseInt( (JOptionPane.showInputDialog( "Enter size of integer list."))); for(i = 1; i <= count; i++) { number = Integer.parseInt( JOptionPane.showInputDialog( "Enter int #" + i + ":")); sum += number; } // The expression (double) sum // converts sum into a double. // (double) is called a "cast" operator. average = (double) sum / count; System.out.println("The average is " + average); } } ------------------------------------------------------- /** * Project Average2 * Class Main * * Compute the average of integers entered * in an option dialog. Use Cancel as a sentinel * to terminate the list. Note that * JOptionPane.showInputDialog returns * a reference to null (no String object returned) * when Cancel is clicked in the input dialog. */ import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { String inputString; int number, count = 0, sum = 0; double average; System.out.println("Enter a list of ints."); System.out.println("Click Cancel to terminate list."); inputString = JOptionPane.showInputDialog( "Enter an int."); while(inputString != null) { number = Integer.parseInt(inputString); sum += number; count++; inputString = JOptionPane.showInputDialog( "Enter an int."); } average = (double) sum / count; System.out.println("The average is " + average); } } ------------------------------------------------------------