Java Reference
In-Depth Information
1 import java.util.Scanner;
2 import java.util.ArrayList;
3
4 public class ReadStringsWithArrayList
5 {
6 public static void main( String [ ] args )
7 {
8 ArrayList<String> array = getStrings( );
9 for( int i = 0; i < array.size( ); i++ )
10 System.out.println( array.get( i ) );
11 }
12
13 // Read an unlimited number of String; return an ArrayList
14 // The minimal I/O details used here are not important for
15 // this example and are discussed in Section 2.6.
16 public static ArrayList<String> getStrings( )
17 {
18 Scanner in = new Scanner( System.in );
19 ArrayList<String> array = new ArrayList<String>( );
20
21 System.out.println( "Enter any number of strings, one per line; " );
22 System.out.println( "Terminate with empty line: " );
23
24 while( in.hasNextLine( ) )
25 {
26 String oneLine = in.nextLine( );
27 if( oneLine.equals( "" ) )
28 break;
29
30 array.add( oneLine );
31 }
32
33 System.out.println( "Done reading" );
34 return array;
35 }
36 }
figure 2.8
Code to read an unlimited number of String s and output them, using an ArrayList
failure to specify the type of objects in the ArrayList declaration is still
allowed, but its use will generate a warning because it removes the ability of
the compiler to detect type mismatches, forcing those errors to be detected
much later by the Virtual Machine when the program is actually run. Sec-
tions 4.6 and 4.8 describe both the old style and the new style.
 
Search WWH ::




Custom Search