8. Use" " and not ' ' for outputting a blank.
on the internet
Following are the available files for this chapter. Everything is self-contained, and nothing is used later in the text.
RandomNumbers.java Contains the code for the example in Figure 2.4. ReadStrings.java Contains the code for the example in Figures 2.6
and 2.7.
ReadStringsWithArrayList.java
Contains the code for the example in Figure 2.8.
MatrixDemo.java Contains the code for the example in Figure 2.9.
Echo.java Contains the code for the example in
Figure 2.10.
ForEachDemo.java Illustrates the enhanced for loop.
DivideByTwo.java Contains the code for the example in Figure 2.11.
MaxTest.java Contains the code for the example in Figures 2.15–2.18.
ListFiles.java Contains the code for the example in Figure 2.19.
DoubleSpace.java Contains the code for the example in Figure 2.20.
exercises
IN SHORT
2.1 List the major differences between reference types and primitive types.
2.2 List five operations that can be applied to a reference type. 2.3 What are the differences between an array and ArrayList? 2.4 Describe how exceptions work in Java.
2.5 List the basic operations that can be performed on Strings. 2.6 Explain the role ofnextandhasNextin theScannertype.
IN THEORY
2.7 Ifxandyhave the values of 5 and 7, respectively, what is output by the following?
System.out.println( x + ' ' + y ); System.out.println( x + " " + y );
2.8 The finally block introduces complications in the Java language specification. Write a program to determine what value is returned by
foo and what exception is thrown by bar in Figure 2.21.
IN PRACTICE
2.9 A checksum is the 32-bit integer that is the sum of the Unicode char- acters in a file (we allow silent overflow, but silent overflow is unlikely if all the characters are ASCII). Two identical files have the same checksum. Write a program to compute the checksum of a file that is supplied as a command-line argument.
figure 2.21
Complications caused by the finally block. public static void foo( )
{ try { return 0; } finally { return 1; } }
public static void bar( ) {
try {
throw new NullPointerException( ); }
finally {
throw new ArithmeticException( ); }
2.10 Modify the program in Figure 2.19 so that if no command-line argu- ments are given, then the standard input is used.
2.11 Write a method that returns trueifString str1is a prefix of String str2. Do not use any of the general string searching routines except charAt. 2.12 Write a routine that prints the total length of the Strings in a String[]
passed as a parameter. Your routine must work unchanged if the parameter is changed to an ArrayList<String>.
2.13 What is wrong with this code?
public static void resize( int [ ] arr ) {
int [ ] old = arr;
arr = new int[ old.length * 2 + 1 ];
for( int i = 0; i < old.length; i++ ) arr[ i ] = old[ i ];
}
2.14 Implement the following methods, that accept an array of double and return the sum, average, and mode (most common item) in the array.
public static double sum( double [ ] arr ) public static double average( double [ ] arr ) public static double mode( double [ ] arr )
2.15 Implement the following methods, that accept a two-dimensional array of doubleand return the sum, average, and mode (most common item) in the two-dimensional array.
public static double sum( double [ ][ ] arr ) public static double average( double [ ][ ] arr ) public static double mode( double [ ][ ] arr )
2.16 Implement the following methods that reverse an array or ArrayList
ofString.
public static void reverse( String [ ] arr ) public static void reverse( ArrayList<String> arr )
2.17 Implement the following methods that return the minimum of the group of items passed as the parameter. In the case of Strings, the minimum is the alphabetically smallest, as determined by compareTo.
public static int min( int [ ] arr ) public static int min( int [ ][ ] arr ) public static String min( String [ ] arr )
2.18 Implement the following method that returns the index of the row that contains the most zeros.
public static int rowWithMostZeros( int [ ] [ ] arr )
2.19 Implement the various hasDuplicatesmethods, which all return true if there are any duplicate entries in the specified group of elements.
public static boolean hasDuplicates( int [ ] arr ) public static boolean hasDuplicates( int [ ][ ] arr ) public static boolean hasDuplicates( String [ ] arr ) public static boolean hasDuplicates( ArrayList<String> arr )
2.20 Implement both howManymethods, which return the number of occur- rences of val in arr.
public static int howMany( int [ ] arr, int val ) public static int howMany( int [ ][ ] arr, int val )
2.21 Implement both countChars methods, which return the number of occurrences of ch in str.
public static int countChars( String str, char ch ) public static int countChars( String [ ] str, char ch )
2.22 Using the StringmethodtoLowerCase, which creates a new Stringthat is the lower case equivalent of an existing String (i.e.,str.toLowerCase()
returns a lower case equivalent of str, while leaving strunchanged), imple- ment the getLowerCaseandmakeLowerCase methods below. getLowerCase
returns a new collection of Strings, while makeLowerCase modifies the existing collection.
public static String [ ] getLowerCase( String [ ] arr ) public static void makeLowerCase( String [ ] arr )
public static ArrayList<String> getLowerCase( ArrayList<String> arr ) public static void makeLowerCase( ArrayList<String> arr )
2.23 MethodisIncreasingreturns true if in each row of the two-dimensional array, all entries monotonically increase, and in each column all entries also monotonically increase. Implement isIncreasing.
public static boolean isIncreasing( int [ ] [ ] arr )
2.24 Implement method startsWithwhich returns an ArrayListcontaining all the Strings inarr that begin with character ch.
2.25 Implement a split method that returns an array of Stringcontain- ing the tokens of the String. Use a Scanner. The method signature forsplit is
public static String [ ] split( String str )
2.26 An alternative to using a Scanner is to use the split method for a
String. Specifically, in the statement below:
String [ ] arr = str.split( "\\s" );
ifstris"this is a test", then arrwill be an array of length four stor- ing the Strings "this", "is", "a", and "test". Modify the code in
Section 2.6.2 to use split instead of a Scanner.
2.27 Both a Scanner andsplit can be configured to use delimiters that are different than the normal whitespace. For instance, in a comma sepa- rated file, the only delimiter is the comma. For split, use "[,]" as the parameter, and for Scanner, at the statement
scan.useDelimiter( "[,]" )
Armed with this information, modify the code in Section 2.6.2 to work for a comma separated line of input.
PROGRAMMING PROJECTS
2.28 Create a data file double1.txtcontaining floating point numbers and suitable for use in Exercise 2.14. Write a method that invokes the functions in that exercise on the data in your file. Make sure there is only 1 item per line and handle all problems.
2.29 Create a data file double2.txt containing floating point numbers in a two dimensional array suitable for use in Exercise 2.15. Write a method that invokes the functions in that exercise on the data in your file. If your code in Exercise 2.15 requires that the two-dimensional array be rectangular, then throw an exception if the data file does not represent a rectangular array, prior to invoking your method.
2.30 Create a data file double3.txt containing floating point numbers in a two dimensional array suitable for use in Exercise 2.15. The numbers in each row should be comma separated. Write a method that invokes the functions in that exercise on the data in your file. If your code in Exercise 2.15 requires that the two-dimensional array be rectangular, then throw an exception if the data file does not represent a rectangu- lar array, prior to invoking your method.
2.31 Write a program that outputs the number of characters, words, and lines in the files that are supplied as command-line arguments. 2.32 In Java, floating-point divide-by-zero is legal and does not result in an
exception (instead, it gives a representation of infinity, negative infin- ity, or a special not-a-number symbol).
a. Verify the above description by performing some floating-point divisions.
b. Write a static divide method that takes two parameters and returns their quotient. If the divisor is 0.0, throw an
ArithmeticException. Is a throws clause needed?
c. Write a main program that calls divide and catches the
ArithmeticException. In which method should the catchclause be placed?
2.33 Implement a text file copy program. Include a test to make sure that the source and destination files are different.
2.34 Each line of a file contains a name (as a string) and an age (as an integer). a. Write a program that outputs the oldest person; in case of ties,
output any person.
b. Write a program that outputs the oldest person; in case of ties, output all oldest people (Hint: Maintain the current group of old- est people in an ArrayList.)
2.35 Write a program that calculates the grades for a course. Your program should prompt the user for the name of a file that stores exam scores. Each line of the file has the following format:
LastName:FirstName:Exam1:Exam2:Exam3
The exams are to be weighted 25% for the first exam, 30% for the second exam, and 45% for the third exam. Based on that, a final grade is to be assigned: A if the total is at least 90, B if it is at last 80, C if it is at least 70, D if it is at least 60, and F otherwise. The highest grade based on the total points is always assigned, so a 75 gets a C.
Your program should output to the terminal a list of students with the let- ter grade, as follows:
LastName FirstName LetterGrade
It should also output to a file, whose name is provided by the user, lines of the form
After it is done, it will output the grade distribution. If the input is
Doe:John:100:100:100 Pantz:Smartee:80:90:80
Then the terminal output is
Doe John A Pantz Smartee B
And the output file will contain
Doe John 100 100 100 100 A Pantz Smartee 80 90 80 83 B A 1 B 1 C 0 D 0 F 0
2.36 Modify Exercise 2.35 to use a vary generous scoring scale in which this high exam score is weighted 45%, the next highest score is 30%, and the low exam score is 25%. Otherwise, the specification is identical.
references