CSC116 Practice Exam 2 - KEY Part I: Vocabulary (10 points) Write the terms defined by the statements below. Cumulative Algorithm 1. An operation in which an overall value is computed incrementally, often using a loop. Relational 2. The < (less than) symbol is an example of what type of operator. Precondition 3. A condition that must be true before a method executes to guarantee that it can perform its task. Roundoff Error 4. A numerical error that occurs because floating-point numbers are stored as approximations rather than as exact values. NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file. True or False true When a Scanner object is passed as a parameter to a method, the input cursor does not reset to the beginning of the File. true When creating a Scanner object to read a file, if the specified input file does not exist, a FileNotFoundException will occur. false true The %8d format specifier results in a right-aligned 8-space wide real number field. (integer field) White box testing cannot test code located in the main() method. False (if/else if) An if/else statement construct is used to choose 0 or 1 of two paths.
Part II: Miscellaneous (4 points) 1. Factor the following code to make it more efficient: if (num < 100 ) { System.out.println( The number is: + num); num *= 2; System.out.println( The new number is: + num); else { System.out.println( The number is: + num); num /= 2; System.out.println( The new number is: + num); System.out.println( The number is: + num); if (num < 100 ) { num *= 2; else { num /= 2; System.out.println( The new number is: + num); 2. Fix the following code: if ( 2 < y <= 8 ) { return true; if ( y > 2 && y <= 8 ) { return true; 3. What type of Java control structure is represented by the following control flow template? do/while Loop
Part III: Assertions (6 points) Identify the various assertions in the following code as being always true, never true, or sometimes true at different points in program execution. The "Point X" comments in the code indicate the points of interest. public static int mystery(scanner console) { int y = console.nextint(); int count = 0; int x = 0; // Point A while (y!= 0) { // Point B if (y == x) { // Point C count++; x = y; y = console.nextint(); // Point D // Point E return count; y == 0 x == 0 x == y Point A SOMETIMES ALWAYS SOMETIMES Point B NEVER SOMETIMES SOMETIMES Point C NEVER NEVER ALWAYS Point D SOMETIMES NEVER SOMETIMES Point E ALWAYS SOMETIMES SOMETIMES
Part IV: Boolean Expressions (10 points) Given the following variable declarations: int x = -5; int y = 10; int z = 20; boolean p = x < y; boolean q = z < x; What is the value of each of the following Boolean expressions? 1. (x <= y) && q true && false = false 2. (y / z > 0) p false true = true 3.!(z % y!= 0)!p &&!(x == z p!= q)!false!true &&!(false true) true false && false true false = true 4. z > y y / (x + 5) == 0 true (java will not evaluate short circuiting so no divide by 0 exception) = true Use De Morgan's laws and negation logic to simplify this Boolean expression. Your final expression should NOT have an! preceding any expression in parentheses.!(b > 0 c!= a && a <= 5)!(b>0) &&!(c!=a && a <=5) b<=0 && (!(c!=a)!(a <=5)) b<=0 && (c==a a>5)
Part V: Loops (15 points) Give the output of each code segment below: Segment 1: Write output here: int count = 0; 10 0 int num = 12; 8 1 do { 6 2 num = num - 2; System.out.println(num + " " + count++); while (count < num / 2); Segment 2: Write output here: int x = 1; 2 2 int y = 1; 4 3 while (x < 12) { 7 4 x = x + y; 11 5 y++; 16 6 System.out.println(x + " " + y);
Consider the following method: public static int mystery(int n) { if (n < 0) { return -1; while ( n > 0) { if (n % 2 == 0) { n = n / 2; else if (n == 1) { return 1; else { n = n * 3 + 1; return 0; For each call below, indicate what value is returned. Method Call Return Value mystery(-1); -1 mystery(0); 0 mystery(1); 1 mystery(2); 1 mystery(10); 1
Part VI: File I/O (20 points) Complete the FileCapitalize class below. In the main() method, create a Scanner object to read from a file named input.txt and create a PrintStream object to write to a file named capitalized.txt. Use try/catch and output an error message if you catch a FileNotFoundException. Call the capitalize() method which will read each line of the input file and write it to the output file in all capital letters. import java.util.*; import java.io.*; public class FileCapitalize { public static void main(string[] args) { try { Scanner infile = new Scanner( new File ("input.txt")); File file = new File ("capitalized.txt"); PrintStream outfile = new PrintStream (file); //can combine this and last line, like infile capitalize(infile, outfile); catch (FileNotFoundException e) { System.out.println("Error: "+ e); //Can use a different error message //read each line in the input file and write it to the output file in all capital letters public static void capitalize (Scanner input, PrintStream output) { while(input.hasnextline()) { String line = input.nextline(); output.println(line.touppercase());
Part VII: Conditional Logic (20 points) 1. Write a method called getstatuslightcolor that returns "red" if the fuel amount of a vehicle is less than 10% of its fuel capacity, "green" otherwise. The fuel amount and fuel capacity should be passed to the method as parameters of type double. public static String getstatuslightcolor(double fuelamount, double fuelcapacity) { String result; if (fuelamount <.10 * fuelcapacity) { result = red ; else { result = green ; return result; 2. A company charges $10 per item to ship an item within the continental U.S., $15 for each item shipped to AK (Alaska) or HI (Hawaii), and $20 for each item shipped out of the country. Complete the method below, which returns the total shipping charge based on the country (and state, if within the U.S.). For example, the method call getshippingcharge(4, USA, NC ) would return 40, getshippingcharge(3, USA, HI ) would return 45, getshippingcharge(5, UK, ) would return 100. It s OK to use magic numbers. public static int getshippingcharge (int numberofitems, String country, String state) { int charge; if (country.equals( USA )) { if (state.equals( AK ) state.equals( HI )) { charge = numberofitems * 15; else { charge = numberofitems * 10; else { charge = numberofitems * 20; return charge;
Part VIII: Random Numbers (15 points) Complete the following program that simulates the flipping of a coin. The coin will be flipped 5 times, after each flip output either Heads or Tails. Generate a random integer, a 1 or a 2, with 1 indicating heads and 2 indicating tails. Do not use magic numbers. import java.util.*; public class CoinFlip { public static final int TAILS = 2; public static final int NUM_FLIPS = 5; public static void main(string[] args) { Random rand = new Random() ; int count = 1 ; while ( count <= NUM_FLIPS ) { // simulate coin flip int flip = _rand.nextint(tails) + 1 ; System.out.print("Flip number " + _count + ": "); if (flip == TAILS ) { System.out.println( _"Tails" ) ; else { System.out.println( "Heads" ) ; count++ ;