Java Reference
In-Depth Information
When you are working with this sample array, if you attempt to refer to list[-1]
or list[5] , you are attempting to access an array element that does not exist. If
your code makes such an illegal reference, Java will halt your program with an
ArrayIndexOutOfBoundsException .
A Complete Array Program
Let's look at a program in which an array allows you to solve a problem that you
couldn't solve before. If you tune in to any local news broadcast at night, you'll hear
them report the high temperature for that day. It is usually reported as an integer, as
in, “It got up to 78 today.”
Suppose you want to examine a series of daily high temperatures, compute the
average high temperature, and count how many days were above that average temper-
ature. You've been using Scanner s to solve problems like this, and you can almost
solve the problem that way. If you just wanted to know the average, you could use a
Scanner and write a cumulative sum loop to find it:
1 // Reads a series of high temperatures and reports the average.
2
3 import java.util.*;
4
5 public class Temperature1 {
6 public static void main(String[] args) {
7 Scanner console = new Scanner(System.in);
8 System.out.print("How many days' temperatures? ");
9 int numDays = console.nextInt();
10 int sum = 0;
11 for ( int i = 1; i <= numDays; i++) {
12 System.out.print("Day " + i + "'s high temp: ");
13 int next = console.nextInt();
14 sum += next;
15 }
16 double average = ( double ) sum / numDays;
17 System.out.println();
18 System.out.println("Average = " + average);
19 }
20 }
Did You Know?
Buffer Overruns
One of the earliest and still most common sources of computer security problems
is a buffer overrun (also known as a buffer overflow ). A buffer overrun is similar
Continued on next page
 
Search WWH ::




Custom Search