School of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Question Sheet 1 Simple Java Programs The following questions are designed to promote understanding of the material in CS1Ah. Your tutor may discuss some of the questions, and some may be set as homework. Work on these questions is not formally assessed, so you may discuss answers with your fellow students (remember that this does not apply to practical exercises). When problems on this sheet are set as homework, there is no reason to copy solutions from somebody else; you should think about the questions yourself, so you can discuss answers at a tutorial. If you have difficulty, you may ask a lab demonstrator for help or consult the solution sheet on the web, when it is issued. 1. Experiment with the programs given in Lecture Note 3. First, type each one in, compile it, and run it. (If you have any difficulty, first work through Practical 2 from the Introduction to the System lectures, and consult a laboratory demonstrator). a) For the SumTwo program in Lecture Note 3, • What happens when you call SumTwo with too many arguments? • What happens when you call it with too few? • What happens when you execute the command java SumTwo 7 david ? b) Modify the DiffSquares program to make a SumSquares program. This should output the sum of the squares of two command line arguments. Change the name of the class, the diffSquares method, and remember to store the new program with the right filename. c) Write a program CalculatePrice.java. This program should have a class called CalculatePrice with a method totalPrice that has parameters baseprice and packingprice. It should return a total price based on adding the two and then calculating VAT (at 17.5%) on the total. Since we use integers, all prices should be given in pence. Write a main function which invokes your totalPrice method. d) Find the documentation of the System class in the Java 1.4 API documentation, beginning from the CS1 web pages. The amount of detail in the API documentation is a bit daunting at first, but will be very useful to you later. Once you have found the documentation for the System class, find the field out. This is a static object which belongs to the PrintStream class. Now find the documentation of PrintStream. How many different print and println methods are there? 1 School of Informatics, University of Edinburgh Computer Science 1 Ah 2. Lecture Note 6 introduces ways of combining Java statements to achieve different control paths in a program. The “flow of control” is the path taken through the program when it runs. Suppose S1, S2, S3 and S4 are Java statements. Test your understanding of Java’s control structures by completing the table below to show the possible paths through the statements given. Some lines have already been filled. Statement Number of paths Possible paths S1 ; S2 ; S3 1 S1 −→ S2 −→ S3 S1 ; { S2 ; S3 } if (x==0) S1 else S2 2 S1, S2 S1 ; if (x==0) S2 else S3 switch (x) { case 0: S1 case 1: S2 ; break; default: S3 } S1 ; while (x<0) {S2 }; S3 3. The greatest common divisor (GCD) of two positve integers a and b is the greatest integer which divides both a and b without remainder. A way of computing the GCD was given by Euclid over 2000 years ago: while b is not zero, repeatedly swap a and b, and set b = b mod a. The answer is the final value of a. a) Write a Java program which reads two integers from the command line and com- putes their GCD, using a static method computeGCD containing a while loop. b) Sometimes we want smaller or larger integers than Java’s primitive types int or long allow. Java has a class java.math.BigInteger for arbitrarily large integers. Read the API documentation for BigInteger and convert your GCD program to read two possibly large integers on the command line, and compute their GCD. Remember to begin your program with an import line. 4. Fill in the types and values of the following Java expressions. Assume that the variable n holds the int value 5. a) 3+4*2 b) (3+4)*2 c) ++n*4 d) n++*4 e) 9.0/5.0 f) n/3 g) (char)(’A’+5) h) 39<14*3 && n==0 i) ++n == n j) n-- == n+1 Now check your answers by writing a program TestExpr.java to confirm the results. The program TestExpr.java should contain a main method with a number of lines which look like this: System.out.println("part a. 3+4*2 = " + (3+4*2) ); (Make sure you understand the three different ways that the addition symbol ”+” is used in this line of program!) Your program will also need to declare a value for the integer n. If the starting value of n is 5, what is the final value of n after executing your program? 2 School of Informatics, University of Edinburgh Computer Science 1 Ah 5. Recall that the positive Fibonacci numbers are given by the sequence 1, 1, 2, 3, 5, 8, . . . , where each successive number is the sum of the two previous. a) Write a program Fibonacci which outputs the first 25 Fibonacci numbers, using a static method printFibs parameterised on the length of the sequence. What goes wrong if you try to print the first 50 numbers, and how might you fix it? b) Write a program which calcluates the limit of the ratio of two sequential Fibonacci numbers. Use an accuracy as good as possible allowed by the primitive type float. What assumptions does your program make about the calculation? 6. In this question you’re asked to write a program called NumbersGame which plays the numbers guessing game: the computer thinks of a number between 1 and 100, and the player has to guess it. The computer displays a message to say if the guess was too low or too high. Finally when the player guesses the right number, the computer displays a count of how many guesses it took. (What’s the largest number of guesses you should ever need?). To think of a random number, you can use the method Math.random() which re- turns a float f such that 0 ≤ f < 1.0. You must scale it and convert to an integer. The methods JOptionPane.showMessageDialog and JOptionPane.showInputDialogmay be used to display windows with messages and with prompts for guesses. To see how to use these methods, look at the example program DiffSquaresSwing.java in the Java/Introduction folder on the CS1 web pages. 7. The appendix to Lecture Note 3 introduces BlueJ, a simple IDE for learning Java. Following the instructions in the note, experiment with BlueJ and the sample projects. a) Experiment with invoking methods on Date objects. Create two objects and verify the behaviour of object identity that you expect. b) Experiment with SpecialDate objects, and setting names for them. When you create a special date for the first time, how is the underlying date created? c) Experiment with Holiday objects. Create a single-day holiday maydayholiday for May day next year (1st May 2003), whose start and end days are the same day, represented by a date object mayday. Using the object inspector, verify the be- haviour of object identity you expect when the underlying date object is changed. 8. Consider the Java class Dog which is given below. A dog has a name and a birth- day. Java represents dates using the class java.util.Calendar, which has a sub- class java.util.GregorianCalendar, used below. import java.util.GregorianCalendar; import java.text.SimpleDateFormat; public class Dog { String name; GregorianCalendar birthday; SimpleDateFormat sdf = new SimpleDateFormat(); /* constructor to make a new dog born today */ public Dog(String n) { 3 School of Informatics, University of Edinburgh Computer Science 1 Ah name = n; birthday = new GregorianCalendar(); } public String getName() { return name; } public String getBirthday() { return sdf.format(birthday.getTime()); } } a) Write a program MyDog.java which takes one argument from the command line, creates a new dog with that name, and prints out a message like “Spot was born on 10/29/01 12:00 AM ” where Spot is your dog’s name and Oct 29 is his birthday. You should not modify the Dog.java file to do this. b) Modify Dog.java to allow dog objects to be created with specified birthdays, adding a new constructor to the class which accepts a calendar parameter. Add another method which returns the dog’s age in years. (You’ll need to check the methods provided in java.util.Calendar to do this, by reading the API docu- mentation). c) Modify your MyDog program to exercise the new features you have aded to Dog. 9. (Continuing Question 8). Design a class called Kennel which has methods: public void dropOff(Dog d); public Dog pickUp(String dogname); public String toString(); so that a dog can be put in the Kennel and then picked up later by calling (for example) k.pickUp("Lassie"); where k is an instance of the Kennel class. You should not be able to pick up dogs that haven’t been dropped off yet. Write a program MyKennel which tests the Kennel class, by making a kennel, putting some dogs into it, showing the contents, then removing some dogs and showing the kennel contents again. Hint: read the documentation for java.util.Hashtable. You don’t need to understand how this class works, only how to use it. 10. Read through the early chapters of your Java textbook, which cover the material that we have covered in lectures so far. Try some exercises which you find interesting. If you have the textbook Java How to Program, work through Chapters 2–6. Contributions from Ross Duncan and Jim O’Donnell. David Aspinall, 2002/10/16 12:26:09. 4