Page 412 - Introduction to Programming with Java: A Problem Solving Approach
P. 412

                378 Chapter 10 Arrays and ArrayLists
 /******************************************************************
*
SpeedDialList2.java
Dean & Dean
This program creates a speed-dial phone number list and
prints the created list. It uses a partially filled array.
******************************************************************/
*
*
*
*
import java.util.Scanner;
public class SpeedDialList2
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String[] phoneList = new String[100]; // phone numbers
int filledElements = 0;
String phoneNum;
// number of phone numbers
// an entered phone number
System.out.print("Enter phone number (or q to quit): ");
phoneNum = stdIn.nextLine();
while (!phoneNum.equalsIgnoreCase("q") &&
        Apago PDF Enhancer
if (phoneNum.length() < 1 || phoneNum.length() > 16)
  filledElements < phoneList.length)
 {
     }
// end class SpeedDialList2
}
// end main
{
 }
else
{
System.out.println("Invalid entry." +
" Must enter between 1 and 16 characters.");
phoneList[filledElements] = phoneNum;
filledElements++;
Update number of filled elements.
System.out.print("Enter phone number (or q to quit): ");
    }
 }
// end while
phoneNum = stdIn.nextLine();
System.out.println("\nSpeed Dial List:");
for (int i=0; i<filledElements; i++)
Array length property does not use ( )’s.
String length
method uses ( )’s.
 {
System.out.println((i + 1) + ". " + phoneList[i]);
  } // end for
Use filledElements for printing the array.
Figure 10.4 SpeedDialList2 program that processes a partially filled array, using the array length property and the String length method









































   410   411   412   413   414