Java Reference
In-Depth Information
In previous chapters, you worked with primitive data types and learned how to construct
your own classes. Recall that a variable of a primitive data type can store only one value
at a time; on the other hand, a class can be defined so that its objects can store more
than one value at a time. This chapter introduces a special data structure called an array,
which allows the user to group data items of the same type and process them in a
convenient way.
Why Do We Need Arrays?
Before we formally define an array, let's consider the following problem. We want to
write a Java program that reads five numbers, finds their sum, and prints the numbers in
reverse order.
In Chapter 5, you learned how to read numbers, print them, and find their sum. What's
different here is that we want to print the numbers in reverse order. We cannot print the
first four numbers until we have printed the fifth, and so on. This means that we need to
store all the numbers before we can print them in reverse order. From what we have
learned so far, the following program accomplishes this task:
//Program to read five numbers, find their sum, and print the
//numbers in the reverse order.
import java.util.*;
public class ReversePrintI
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int item0, item1, item2, item3, item4;
int sum;
System.out.println("Enter five integers: ");
item0 = console.nextInt();
item1 = console.nextInt();
item2 = console.nextInt();
item3 = console.nextInt();
item4 = console.nextInt();
sum = item0 + item1 + item2 + item3 + item4;
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in reverse order are: ");
System.out.println(item4 + " " + item3 + " " + item2
+ " " + item1 + " " + item0);
}
}
 
Search WWH ::




Custom Search