CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2016 Name: Question Value Score 1 10 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 10 10 10 TOTAL 100 Please answer questions in the spaces provided. Please be legible. If you make a mistake or need more space, use backs of pages - clearly indicate where the answer can be found. Good luck and best wishes for a great summer!
1. ( / 10) What gets printed? Please show output as it will appear, or indicate NO OUTPUT. If there is an infinite loop, be sure to show some lines of the output followed by INFINITE LOOP. int a = 4; do a--; System.out.println(a); while (a < 4) Output: 3 2 1 INFINITE LOOP String[] notes = "do", "re", "mi"; for (String word : notes) System.out.println ("Tra la la " + word); Output: tra la la do tra la la re tra la la mi int size = 10; do System.out.print(size + " => "); int category = size / 5; switch(category) case 0: System.out.println ("S"); break; case 1: System.out.println ("M"); break; default: System.out.println ("L"); size = size - 2; while (size > 2); Output: 10 => L 8 => M 6 => M 4 => S int a = 4; for (int a = 4; a < 4; a--) System.out.println(a); Output: NO OUTPUT
2. ( / 10) Suppose you are drawing in a Graphics context at position (x,y) an emoji that is controlled by a boolean variable happy. When happy is true, it should look like it is smiling; when false, it should look like it is frowning. Assume that the face and eyes are already drawn, so you just need to draw the mouth as an arc facing up or down. Here is the code using if/else: if (happy) page.drawarc (x+15, y+30, 20, 10, 180, 180); else page.drawarc (x+15, y+30, 20, 10, 0, 180); * Rewrite the above code using the conditional operator. (i.e., in a single line of code, without using if/else). page.drawarc (x+15, y+30, 20, 10, happy? 180: 0, 180); b) Suppose you would like to generate a random inspirational message. You start by creating an array containing a list of possible messages: String[] mycliche = "Life is beautiful", "Keep calm and carry on", "Live, laugh, love", "Today is the first day of the rest of your life" ; // add your own, if you feel like it! Write a code fragment that uses a randomly generated index into this array to print one of the above messages. Your choice whether to use an object from the Random class or the random() method from the Math class. Be sure your code works fine if you add more messages to the array (for example, if you add a fifth message in the array above). Random rand = new Random(); int choice= rand.nextint(mycliche.length); System.out.println(myCliche[choice]);
3. ( / 10) Consider the following program: //************************************************************** // SomethingToDoWithFiles.java Author: MAP //************************************************************** import java.util.scanner; import java.io.*; public class SomethingToDoWithFiles public static void main (String[] args) throws IOException String line1, line2; Scanner filescan1, filescan2; File myfile1 = new File("sample1.txt"); filescan1 = new Scanner (myfile1); File myfile2 = new File("sample2.txt"); filescan2 = new Scanner (myfile2); outfile = new PrintWriter("data-out.txt"); while (filescan1.hasnext() && filescan2.hasnext()) line1 = filescan1.nextline(); line2 = filescan2.nextline(); outfile.print(line1.charat(0) + "**" + line2.charat(0)); outfile.println(filescan2.hasnext()? "Down!": "Up!"); outfile.close(); System.out.println(fileScan2.hasNext()? "Up!": "Down!"); a) Suppose the file sample1.txt and sample2.txt are as shown above. Show the OUTPUT and the contents of the file data-out.txt after execution of the program. OUTPUT: data-out.txt Down! sample1.txt down came the rain and washed the spider out. d**ot**aw**aup! sample2.txt out came the sun and washed out all the rain b) Give an example of a situation that could cause IOExceptions in the above code. file not found for the Scanner cannot do input (OR bad file name for the PrintWriter cannot create the file)
4. ( / 10) a) Write a Java method max() with three parameters of type double that returns a value of type double that is the largest of the three given values. For example, max(35.2, 45.7, 22.8) should return 45.7. Note that the method should not print anything. public double max(double a, double b, double c) double max = a; if (b > max) max = b; if (c > max) max = c; return max; a) Write a Java method countvowels() with one parameter, a String that returns the number of vowels (an integer) in the given String. For example, countvowels("the end is near") should return 5. Note that the method should not print anything. public int countvowels(string word) int count = 0; for (char c: word) if (c == a c == e c == i c == o c == u ) count ++; return count;
5. ( / 10) a) Trace through the following code and show what gets printed. int[] a = 100, 200, 300, 400; int[] b = 1000, 2000, 3000, 4000; int[] c = b; for (int i=0; i<a.length; i++) b[i] = a[i]; a[1] = 4; b[2] = 5; c[3] = 6; for (int x: a) System.out.print(x + " "); System.out.println(); for (int x: b) System.out.print(x + " "); System.out.println(); for (int x: c) System.out.print(x + " "); System.out.println(); Output: 100 4 300 400 100 200 5 6 100 200 5 6 b) Suppose an array of int named list has been declared, instantiated, and initialized. Write a code fragment to print the contents of array list backwards. for (int i = list.length - 1; i >=0; i--) System.out.println(list[i]);
6. ( / 10) Consider the following program: // ProductCodes.java Author: Lewis/Loftus import java.util.scanner; public class ProductCodes //----------------------------------------------------------------- // Counts the number of product codes that are entered with a // zone of R and and district greater than 2000. //----------------------------------------------------------------- public static void main(string[] args) String code; char zone; int district, valid = 0, banned = 0; Scanner scan = new Scanner(System.in); System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); while (!code.equals("xxx")) try à zone = code.charat(9); catch à district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); System.out.println("# of valid codes entered: " + valid); System.out.println("# of banned codes entered: " + banned); a) Give a examples of product code inputs that would cause the program to _ TTTTTTTTTTTT throw a NumberFormatException TTT throw a StringIndexOutOfBoundsException AAA3446RRR NOT throw any exception but be counted as banned XXX cause the program to terminate, without error. b) Suppose you would like to catch and handle NumberFormatException by skipping this input using the following catch clause: catch (NumberFormatException exception) System.out.println("Bad code: " + code); Annotate ProductCodes.java to show exactly how the try/catch block should be placed.
7. ( / 10) Consider the following program: public class TwoDArray public static void main (String[] args) int[][] table = new int[3][9]; for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; System.out.print ("# \t"); for (int col=0; col < table[0].length; col++) System.out.print (col + "\t"); System.out.println(); System.out.print ("--+-----"); for (int col=0; col < table[0].length; col++) System.out.print ("-----"); System.out.println(); for (int row=0; row < table.length; row++) System.out.print (row + " \t"); for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); We would like to modify the program to: (1) change array size; and (2) label rows/columns so that the output would now look EXACTLY like this: # 0 1 2 3 4 5 6 7 8 --+-------------------------------------------------------- 0 0 1 2 3 4 5 6 7 8 1 10 11 12 13 14 15 16 17 18 2 20 21 22 23 24 25 26 27 28 a) In the above output, circle entries corresponding to table[0][2] and table[2][3]. b) Annotate the code so that it works as described in (1) and (2) above
8. ( / 10) Complete the java code below so that it prints a table for the Investment problem: You put an initial amount into a bank account that earns 5% interest per year. Show the yearly returns on your investment until it doubles. For example, if the user inputs 10000 as the initial amount, a table such as the one shown here would be printed. import java.text.numberformat; import java.util.scanner; public class Investment public static void main (String[] args) Scanner scan = new Scanner(System.in); year interest balance 0 $10,000.00 1 $500.00 $10,500.00 2 $525.00 $11,025.00 3 $551.25 $11576.25 4 $578.81 $12,155.06 (keep going until balance >= $20000) System.out.print("Enter initial balance:"); double initial = scan.nextdouble(); int year = 0; double rate = 0.05; double balance = initial; NumberFormat money = NumberFormat.getCurrencyInstance(); System.out.println("year\tinterest\tbalance"); System.out.println (year + "\t" + " " + "\t" + money.format(balance)); double interest; double target = 2 * initial; while (balance < target) year++; interest = balance * rate; balance += interest; System.out.println (year + "\t" + money.format(interest) + "\t" + money.format(balance));
9. ( / 10) Write a complete Java program consisting of a class Shoe and a client class named Wishlist. The Shoe class should contain instance variables representing the following shoe data: manufacturer- a String, eg "Sofft" or "Steve Madden" name - a String, eg "Madeline" or "Realove" price - a f (use double), eg: 79.95 SKU number - an integer, eg: 8112951 (SKU is displayed right above price in picture below) The Shoe class should have a constructor, accessor and mutator methods for the price, and a tostring() method. Do not write code for any additional methods (no need to write accessors and mutators for all the other instance variables). The client class Wishlist should implement the following algorithm: o Instantiate three variables of the Shoe class named s1, s2, s3 (make up values for the data) o Print the info of s1, s2, s3 o Change the price of s1 to $29.99 o Print the total price of s1, s2, s3 Write the complete code for the two classes in the next two pages. Notes: It is NOT necessary to include comments with your code, but be sure to use good indentation. Formatting a number as a currency: if you need a reminder, see previous question Write the complete code for the two classes in the next two pages. èè
import java.text.numberformat; public class Shoe private String manufacturer; private String name; private double price; private int sku; // Constructor: with all the data public Shoe(String m, String n, double p, int s) manufacturer = m; name = n; price = p; sku = s; public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); return name + " by " + manufacturer + ", SKU: " + sku + " " + fmt.format(price); public void setprice(double p) price = p; public double getprice() return price;
import java.text.numberformat; public class Wishlist public static void main(string[] args) Shoe s1, s2, s3, s4; s1 = new Shoe("Nike", "Air", 80, 833); s2 = new Shoe("Asics", "Gel Nimbus", 100, 329); s3 = new Shoe("Madden", "Realove", 30, 440); System.out.println(s1); System.out.println(s2); System.out.println(s3); s1.setprice(29.99); NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println("Total price of shoes"); double total = s1.getprice() + s2.getprice() + s3.getprice(); System.out.println(fmt.format(total));
10. ( / 10) Draw the UML class diagram for the previous problem (Shoe + Wishlist). Wishlist main(args: String[]): void Shoe manufacturer: String name: String price: double sku: int tostring: String getprice(): double setprice(x: double): void