Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Laboratory 6 Lesson 6-2 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Lesson 6-3 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Lesson 6-4 Exercise 1 Exercise 2 Exercise 3 Exercise 4 Exercise 5 Exercise 6 Exercise 7 Lesson 6-5 Exercise 1 Exercise 2 Exercise 3 Lesson 6-6 Exercise 1 Exercise 2 Exercise 3 Solutions Lesson 6-2 Exercise 1: // Application HiScore reads and prints three test scores. // The largest value of the three is printed with an // appropriate message // Assumption: The scores are unique import java.util.Scanner; public class HiScore { static int largest(int one, int two, int three) { int highest = 0; if (one > two) highest = one; else highest = two; if (three > highest) highest = three; return highest; } public static void main(String[] args) { Scanner inData = new Scanner(System.in); int score1; int score2; int score3; int count = 1; while( count <= 6 ) { System.out.println( "Run #" + count ); System.out.println( "--------------"); // Prompt for and read in scores System.out.println("Enter three test scores."); score1 = inData.nextInt(); score2 = inData.nextInt(); score3 = inData.nextInt(); System.out.println("The test scores are " + score1 + ", " + score2 + ", " + score3); System.out.println("The highest is " + largest(score1, score2, score3)); System.out.println(); count++; } } } The program output is Run #1 -------------Enter three test scores. 100 80 70 The test scores are 100, 80, 70 The highest is 100 Run #2 -------------Enter three test scores. 100 70 80 The test scores are 100, 70, 80 The highest is 100 Run #3 -------------Enter three test scores. 70 80 100 The test scores are 70, 80, 100 The highest is 100 Run #4 -------------Enter three test scores. 80 70 100 The test scores are 80, 70, 100 The highest is 100 Run #5 -------------Enter three test scores. 80 100 70 The test scores are 80, 100, 70 The highest is 100 Run #6 -------------Enter three test scores. 70 100 80 The test scores are 70, 100, 80 The highest is 100 Exercise 2: // Application HiScore reads and prints three test scores. // The largest value of the three is printed with an // appropriate message // Assumption: The scores are unique import java.util.Scanner; public class HiScore { static int largest(int one, int two, int three) { int highest = 0; if (one > two) highest = one; else highest = two; if (three > highest) highest = three; return highest; } public static void main(String[] args) { Scanner inData = new Scanner(System.in); int score1; int score2; int score3; int count = 1; int numberOfDataSets; System.out.println("Enter the number of data sets."); numberOfDataSets = inData.nextInt(); while( count <= { numberOfDataSets ) System.out.println( "Run #" + count ); System.out.println( "--------------"); // Prompt for and read in scores System.out.println("Enter three test scores."); score1 = inData.nextInt(); score2 = inData.nextInt(); score3 = inData.nextInt(); System.out.println("The test scores are " + score1 + ", " + score2 + ", " + score3); System.out.println("The highest is " + largest(score1, score2, score3)); System.out.println(); count++; } } } The program gives the same results. See Exercise 1. Exercise 3: The following is the revised test driver for the Distance class that uses a count-controlled loop: import java.util.Scanner; // TestDistance is a driver for class Distance public class TestDistance2 { // prints distance to the screen // tests 'get' methods public static void printDistance( String title, Distance d ) { System.out.print( title ); System.out.print( d.getFeet() + "[ft.] "); System.out.print( d.getYards() + "[yd.] " ); System.out.println( d.getMiles() + "[mi.] " ); System.out.println(); } // prompts and reads in feet, yards, and miles // creates and returns a new Distance object // this method created to avoid code redundancy within the loop public static Distance readInDistance( String prompt ) { Scanner inData = new Scanner(System.in); System.out.println( prompt ); int feet = inData.nextInt(); int yards = inData.nextInt(); int miles = inData.nextInt(); return new Distance( feet, yards, miles ); } public static void main(String[] args) { //test the default constructor //-----------------------------System.out.println("----------------------------"); System.out.println("Testing Default constructor:"); System.out.println("----------------------------"); // default distance Distance distance = new Distance(); // print the default distance printDistance("Default Distance: ", distance ); // test addDistance method // add some distance to default distance System.out.println("Add a distance: 5280[ft.] 1760[yd.] 1[mi.]"); // distance to be added to the default distance Distance temp = new Distance(5280, 1760, 1); // show it in normalized form printDistance("Normalized form: ", temp ); // add two distances Distance add = distance.addDistance(temp); // show the result in normalized form printDistance("Normalized the result distance: ", add ); System.out.println(); System.out.println(); // test the parameterized constructor //-----------------------------------System.out.println("----------------------------------"); System.out.println("Testing Parameterized constructor:"); System.out.println("----------------------------------"); System.out.println(); int count = 1; Scanner inData = new Scanner(System.in); while( count <= 3 ) { // prompt and read in a distance Distance distance1 = readInDistance("Enter distance (feet yards miles): "); System.out.print("Normalized Distance 1: "); System.out.println( distance1.toString() ); System.out.println(); // read in another distance to be added to the above distance Distance temp1 = readInDistance("Enter another distance (feet yards miles): "); // show it in normalized form System.out.print("Normalized form: "); System.out.println( temp1.toString() ); System.out.println(); // test addDistance method // add two distances Distance add1 = distance1.addDistance( temp1 ); // print the result distance; test toString method System.out.print ( "The normalized result of adding two distances: " ); System.out.println( add1.toString() ); System.out.println(); System.out.println(); count++; } } } Exercise 4: ---------------------------Testing Default constructor: ---------------------------Default Distance: 0[ft.] 0[yd.] 0[mi.] Add a distance: 5280[ft.] 1760[yd.] 1[mi.] Normalized form: 0[ft.] 0[yd.] 3[mi.] Normalized the result distance: 0[ft.] 0[yd.] 3[mi.] ---------------------------------Testing Parameterized constructor: ---------------------------------Enter distance (feet yards miles): 152 5232 0 Normalized Distance 1: 2[ft.] 2[yd.] 3[mi.] Enter another distance (feet yards miles): 5280 1760 1 Normalized form: 0[ft.] 0[yd.] 3[mi.] The normalized result of adding two distances: 2[ft.] 2[yd.] 6[mi.] Enter distance (feet yards miles): 31 1751 2 Normalized Distance 1: 1[ft.] 1[yd.] 3[mi.] Enter another distance (feet yards miles): 1751 31 9 Normalized form: 2[ft.] 614[yd.] 9[mi.] The normalized result of adding two distances: 0[ft.] 616[yd.] 12[mi.] Enter distance (feet yards miles): 100 2000 1 Normalized Distance 1: 1[ft.] 273[yd.] 2[mi.] Enter another distance (feet yards miles): 1000 100 10 Normalized form: 1[ft.] 433[yd.] 10[mi.] The normalized result of adding two distances: 2[ft.] 706[yd.] 12[mi.] Lesson 6-3 Exercise 1: The following is the expression that returns true if ‘value’ is not zero. while ( value != 0 ) Exercise 2: The loop body will resemble while ( value != 0 ) { if ((value % 2) == 0) evenCount = evenCount + 1; else oddCount = evenCount + 1; System.out.println("Enter an integer value or 0 to stop"); value = inData.nextInt(); } Exercise 3: The following are the output statements that print the number of odd values and the number of even values. System.out.println( "Number of even numbers: " + evenCount ); System.out.println( "Number of odd numbers: " + oddCount ); A following is a sample program for Exercises 1, 2, and 3. import java.util.Scanner; public class OddEven { public static Scanner inData; public static void main(String[] args) { int value; int oddCount = 0; int evenCount = 0; inData = new Scanner(System.in); System.out.println("Enter an integer value or 0 to stop"); value = inData.nextInt(); while ( value != 0 )/* TO BE FILLED IN: Exercise 1 */ { /* TO BE FILLED IN: Exercise 2 */ if ((value % 2) == 0) evenCount = evenCount + 1; else oddCount = evenCount + 1; System.out.println("Enter an integer value or 0 to stop"); value = inData.nextInt(); } /* TO BE FILLED IN: Exercise 3 */ System.out.println( "Number of even numbers: " + evenCount ); System.out.println( "Number of odd numbers: " + oddCount ); } } Exercise 4: The following data values were used. 33 44 55 -66 1 -2 3 8 -9 100 -99 88 0 The following is the program output. Number of even numbers: 6 Number of odd numbers: 6 Lesson 6-4 Exercise 1: Scanner firstIn; PrintWriter firstOut; Exercise 2: firstIn = new Scanner( new File("inData") ); firstOut = new PrintWriter( new FileWriter( "outData" )); Exercise 3: while ( firstIn.hasNextInt() ) Exercise 4: value = firstIn.nextInt(); Exercise 5: firstOut.println( "The sum of the values is: " + sum ); Exercise 6: firstIn.close(); firstOut.close(); The following is a sample program for Exercises 1 – 6. import java.io.*; import java.util.Scanner; public class ReadData { public static void main(String[] args) throws IOException { /* TO BE FILLED IN: Exercise 1 */ Scanner firstIn; PrintWriter firstOut; /* TO BE FILLED IN: Exercise 2 */ firstIn = new Scanner( new File("inData") ); firstOut = new PrintWriter( new FileWriter( "outData" )); int count = 0; int value; int sum = 0; while ( firstIn.hasNextInt() ) /* TO BE FILLED { value = firstIn.nextInt();/* TO BE FILLED IN: sum = sum + value; count++; } /* TO BE FILLED IN: Exercise 5 */ firstOut.println( "The sum of the values is: " firstIn.close();/* TO BE FILLED IN: Exercise 6 firstOut.close(); } } Exercise 7: The following is the file content. The sum of the values is: 719 IN: Exercise 3 */ Exercise 4 */ + sum ); */ Lesson 6-5 Exercise 1: The following is the last line written to data.out. Line 84 contains 2 blanks. Exercise 2: The IOLoop application is written entirely within the main method. The IOLoopA introduces a new method, getBlanks, and the program’s functionality is split between methods. IOLoopA is easier to understand. Splitting the program functionality into several smaller methods could be beneficial. First, it is much easier understand a smaller method than a large code segment. A well written method is usually reusable without modification. A method is also likely to prevent code redundancy within the same program (rather than writing the same code segment several times within a main method, the code segment can be used to create a separate method that then can be called from the main). Exercise 3: // Application IOLoopA counts the number of blanks per line // and estimates the number of words. import java.io.*; import java.util.Scanner; public class IOLoopA { public static Scanner inFile; public static PrintWriter outFile; public static int getBlanks(String inputString) { // Method getBlanks returns the number of blanks // in parameter inputString int blankCount = 0; int index = inputString.indexOf(' '); while (index != -1) { blankCount++; if (inputString.length() != 1) { inputString = inputString.substring(index+1, inputString.length()); index = inputString.indexOf(' '); } else index = -1; } return blankCount; } public static void main(String[] args) throws IOException { int lineCount = 0; int blankCount; String inputString; inFile = new Scanner(new FileReader("history.dat")); outFile = new PrintWriter(new FileWriter("data.out")); int wordCount = 0; while (inFile.hasNextLine()) { inputString = inFile.nextLine(); lineCount++; blankCount = getBlanks(inputString); outFile.println("Line " + lineCount + " contains " + blankCount + " blanks."); wordCount += blankCount; } wordCount += lineCount; outFile.println(); outFile.println("The approximate number of words in the file: " + wordCount ); outFile.close(); inFile.close(); } } The last line written to data.out is now: The approximate number of words in the file: 754 Lesson 6-6 Exercise 1: The file name was incorrectly specified. Change "SumNum.d1" to "SumNums.d1". Exercise 2: The program adds the value of the input number to the count. Instead, it should increase the count by 1. Change count = count + number; to count = count + 1; Exercise 3: The first number read in from the input file is never counted. If the first number in the input file is negative, the error will not show. The logic error will only be noticed if the first number in the input file is positive. To correct the problem, the first line in the body of the while loop should be moved to the bottom of the while body, so that it becomes the last line within the loop. A sample program for Exercises 1 – 3 is // Program SumNums reads and counts nonnegative integers until // the end of file is reached on file SumNums.D1 import java.io.*; import java.util.Scanner; public class SumNums { public static Scanner inFile; public static void main(String[] args) throws IOException { inFile = new Scanner(new FileReader("SumNums.d1")); int number; // input value int count; // number of positive values number = inFile.nextInt(); count = 0; while (number != 0) { if (number > 0) count = count + 1; number = inFile.nextInt(); } System.out.println("The number of nonnegative integers is " + count); } }