simple java programs - university of edinburghschool of informatics, university of edinburgh...

12
School of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set for CS1Ah Question Sheet 1. You should only consult these solutions after attempting the exercises. Notice that the solutions are samples — alternative answers may be possible. Java programs for the solutions are available on-line at: http://www.inf.ed.ac.uk/teaching/classes/cs1/CS1/Ah/Questions/Java/SimpleJavaProgs 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? The extra arguments are simply ignored: java SumTwo 3 4 5 prints the answer 7. What happens when you call it with too few? If you execute the command java SumTwo 3 the system responds with a long error message: the most important part of the message is the bit that says Array index out-of-bounds exception. This kind of error is called a run-time error since it happens when you run the program. The error is caused by the expression args[1]. The variable args is a data structure called an array which has successive elements args[0], args[1], . . . , for each argument that is given on the command line (notice how arrays begin counting from 0). If there is only one argument, only args[0] is defined, and attempting to access other components of the array will give an error message. We will study arrays in a lecture soon. What happens when you execute the command java SumTwo 7 david ? You get another error message. It looks like this: Exception in thread "main" java.lang.NumberFormatException: david at java.lang.Integer.parseInt(Integer.java:405) at java.lang.Integer.parseInt(Integer.java:454) at SumTwo.main(SumTwo.java:6) Errors in Java are called exceptions. The bold part of the message is the exception name. The name suggests that there was a mistake in the format of a number, and shows you the number “david” which was problematical. The remaining parts of the error message tell you where the error was encountered in the program, and is called a stack trace. It tells you which methods were active when the error was encountered. 1

Upload: dohanh

Post on 30-Jan-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

CS1Ah Solution Sheet 1

Simple Java Programs

This is a solution set for CS1Ah Question Sheet 1. You should only consult thesesolutions after attempting the exercises. Notice that the solutions are samples —alternative answers may be possible.

Java programs for the solutions are available on-line at:http://www.inf.ed.ac.uk/teaching/classes/cs1/CS1/Ah/Questions/Java/SimpleJavaProgs

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 fromthe Introduction to the System lectures, and consult a laboratory demonstrator).

a) For the SumTwoprogram in Lecture Note 3,

• What happens when you call SumTwowith too many arguments?

The extra arguments are simply ignored: java SumTwo 3 4 5 prints the answer 7.

• What happens when you call it with too few?If you execute the command java SumTwo 3 the system responds with a long errormessage: the most important part of the message is the bit that says Array indexout-of-bounds exception. This kind of error is called a run-time error since ithappens when you run the program. The error is caused by the expression args[1] .The variable args is a data structure called an array which has successive elementsargs[0] , args[1] , . . . , for each argument that is given on the command line (noticehow arrays begin counting from 0). If there is only one argument, only args[0] isdefined, and attempting to access other components of the array will give an errormessage. We will study arrays in a lecture soon.

• What happens when you execute the command java SumTwo 7 david ?You get another error message. It looks like this:

Exception in thread "main" java.lang.NumberFormatException : davidat java.lang.Integer.parseInt(Integer.java:405)at java.lang.Integer.parseInt(Integer.java:454)at SumTwo.main(SumTwo.java:6)

Errors in Java are called exceptions. The bold part of the message is the exceptionname. The name suggests that there was a mistake in the format of a number, andshows you the number “david ” which was problematical.The remaining parts of the error message tell you where the error was encounteredin the program, and is called a stack trace. It tells you which methods were activewhen the error was encountered.

1

Page 2: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

b) Modify the DiffSquares program to make a SumSquares program. This shouldoutput the sum of the squares of two command line arguments. Change the nameof the class, the diffSquares method, and remember to store the new programwith the right filename.

� �// SumSquares.java: calculate the sum of two squares

class SumSquares {static int sumSquares( int a, int b) {

int asquare;int bsquare;asquare = a * a;bsquare = b * b;return asquare + bsquare;

}public static void main(String[] args) {

int x = Integer.parseInt(args[0]);int y = Integer.parseInt(args[1]);System.out.print( "The sum of squares is: " );System.out.println(sumSquares(x,y));

}}

c) Write a program CalculatePrice.java . This program should have a class calledCalculatePrice with a method totalPrice that has parameters baseprice andpackingprice . It should return a total price based on adding the two and thencalculating VAT (at 17.5%) on the total. Since we use integers, all prices should begiven in pence. Write a main function which invokes your totalPrice method.

� �// CalculatePrice.java: calculate VAT on base price & packing

class CalculatePrice {static int totalPrice( int baseprice, int packingprice) {

int vat = (baseprice + packingprice) * 175 / 1000;return baseprice + packingprice + vat;

}public static void main(String [] args) {

int base = Integer.parseInt(args[0]);int packing = Integer.parseInt(args[1]);

System.out.println(totalPrice(base,packing));}

} 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

2

Page 3: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

is a bit daunting at first, but will be very useful to you later. Once you havefound the documentation for the System class, find the field out . This is a staticobject which belongs to the PrintStream class. Now find the documentation ofPrintStream . How many different print and println methods are there?

There are 9 print methods and 10 println methods (why one more?). Each methodhas approximately the same kind of behaviour, but must be duplicated because the typesof its arguments are different, which means that the precise behaviour is different. Theway that an integer is displayed is different to the way that a floating point number isdisplayed, for example. When you use print or println , the compiler automaticallyselects the correct method according to the type of the arguments you write. This use ofthe same name for different methods is called method overloading.

2. Lecture Note 6 introduces ways of combining Java statements to achieve differentcontrol paths in a program. The “flow of control” is the path taken through the programwhen it runs. Suppose S1, S2, S3 and S4 are Java statements. Test your understandingof Java’s control structures by completing the table below to show the possible pathsthrough 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 } 1 S1 −→ S2 −→ S3

if (x==0) S1 else S2 2 S1, S2

S1 ; if (x==0) S2 else S3 2 S1 −→ S2, S1 −→ S3

switch (x) {case 0: S1

case 1: S2 ; break;default : S3 }

3 S1 −→ S2, S2, S3

S1 ; while (x<0) { S2 } ; S3 n+1 S1(−→ S2)n −→ S3

3. The greatest common divisor (GCD) of two positve integers a and b is the greatestinteger which divides both a and b without remainder. A way of computing the GCDwas 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 orlong allow. Java has a class java.math.BigInteger for arbitrarily large integers.Read the API documentation for BigInteger and convert your GCD program toread two possibly large integers on the command line, and compute their GCD.Remember to begin your program with an import line.

3

Page 4: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

Here is the BigInteger version of the GCD program:� �import java.math.BigInteger;public class GCD {

static BigInteger computeGCD(BigInteger a, BigInteger b) {while (!b.equals(BigInteger.ZERO)) {

BigInteger tmp = b;b = a;a = tmp;b = b.mod(a);

}return a;

}public static void main(String[] args) {

BigInteger a = new BigInteger(args[0]);BigInteger b = new BigInteger(args[1]);BigInteger gcd = computeGCD(a,b);System.out.println( "The greatest common divisor of "

+ a.toString() + " and "+ b.toString() + " is "+ gcd.toString());

}}

4. Fill in the types and values of the following Java expressions. Assume that thevariable n holds the int value 5.

a) 3+4*2b) (3+4)*2c) ++n*4

d) n++*4e) 9.0/5.0f) n/3

g) (char)(’A’+5)h) 39<14*3 && n==0i) ++n == n

j) n-- == n+1

Solutions:

a) 11 (int)b) 14 (int)c) (n+1)*4, or 24

(int)d) n*4, or 24 (int)e) 1.8 (double)

f) n div 3, or 2 (int)g) ’F’ (char)h) false

i) true (boolean)j) true (boolean)

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 lineswhich 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 ”+” isused in this line of program!) Your program will also need to declare a value for theinteger n. If the starting value of n is 5, what is the final value of n after executing yourprogram?

4

Page 5: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

The final value of n is 7.� �class TestExpr {

public static void main(String[] args) {int n = 5;System.out.println( "part a. 3+4*2 = " + (3+4*2) );System.out.println( "part b. (3+4)*2 = " + ((3+4)*2) );System.out.println( "part c. ++n * 4 = " + (++n*4) );System.out.println( "part d. n++ * 4 = " + (n++*4) );System.out.println( "part e. 9.0/5.0 = " + (9.0/5.0));System.out.println( "part f. n/3 = " + (n/3));System.out.println( "part g. (char)(’A’+5) = "

+ ( char )(’A’+5));System.out.println( "part h. (39<14*3 && n == 0) = "

+ (39<14*3 && n == 0));System.out.println( "part i. (++n == n) = "

+ (++n == n));System.out.println( "part j. (n-- == n+1) = "

+ (n-- == n+1));System.out.println( "Final value of n is " + n);

}}

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, usinga static method printFibs parameterised on the length of the sequence. Whatgoes wrong if you try to print the first 50 numbers, and how might you fix it?

5

Page 6: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

If we try to print the first 50 numbers, we see an overflow on the 47th number, whichis too large to represent as an int . This could be fixed by using the BigInteger classmentioned above.� �

// Fibonacci.java: Print Fibonacci numbers.

class Fibonacci {static void printFibs( int length) {

int n1 = 0, n2 = 1;System.out.print(n1);length -= 1;while (length > 0) {

System.out.print( ", " + n2);int tmp = n1;n1 = n2;n2 = tmp + n2;length--;

}System.out.println();

}public static void main(String[] args) {

printFibs(25);}

}

b) Write a program which calcluates the limit of the ratio of two sequential Fibonaccinumbers. Use an accuracy as good as possible allowed by the primitive typefloat . What assumptions does your program make about the calculation?

6

Page 7: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

The solution below assumes that the ratio converges within the accuracy of a floatbefore the Fibonacci numbers overflow the int type.� �

// Ratio.java: Calculate limiting ratio of Fibonacci numbers

class Ratio{public static void main(String[] args) {

// begin from position 1,1,2int n1 = 1, n2 = 2, t;float oldratio = ( float )1.0;float ratio = ( float )1.0/( float )2.0;

while (ratio != oldratio){t = n2;n2 = n1 + n2;n1 = t;oldratio = ratio;ratio = ( float )n1/( float )n2;

}System.out.print( "The limit of the ratio is " );System.out.println(ratio + " to float accuracy." );

}}

6. In this question you’re asked to write a program called NumbersGame which playsthe numbers guessing game: the computer thinks of a number between 1 and 100, andthe player has to guess it. The computer displays a message to say if the guess wastoo low or too high. Finally when the player guesses the right number, the computerdisplays a count of how many guesses it took. (What’s the largest number of guessesyou 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. Themethods JOptionPane.showMessageDialog and JOptionPane.showInputDialog maybe used to display windows with messages and with prompts for guesses. To see howto use these methods, look at the example program DiffSquaresSwing.java in theJava/Introduction folder on the CS1 web pages.

7

Page 8: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

Here’s the implementation of NumbersGame.java . If you’re guessing optimally, you divide thesearch space in half each time, so you should never need more than dlog2(100)e = 7 guesses.� �

/* NumbersGame.java: guess the number I’m thinking of** Author: David Aspinall* Copyright: University of Edinburgh* Version: $Id: NumbersGame.java,v 1.2 2001/11/06 16:04:36 da Exp $**/

import javax.swing.JOptionPane;

class NumbersGame {static int random() {

// Return an int between 1 and 100return 1 + ( int )(Math.random() * 100);

}static int inputNumber(String message) {

return Integer.parseInt(JOptionPane.showInputDialog( null , message));

}static void showMessage(String message, String title) {

JOptionPane.showMessageDialog(null , message, title,

JOptionPane.PLAIN_MESSAGE);}public static void main(String[] args) {

showMessage("I’m going to think of a number between\n"+ "1 and 100, and you have to guess what it is.\n\n"+ "Are you ready?" , "Numbers Game" );

int mynumber = random();int yourguess = 0;int numberofguesses = 0;

while (yourguess != mynumber) {yourguess = inputNumber( "What is your guess?" );numberofguesses++;if (yourguess < mynumber) {

showMessage( "No, that’s too low!" , "Bad guess!" );};if (yourguess > mynumber) {

showMessage( "No, that’s too high!" , "Bad guess!" );}

}showMessage( "Yes! I was thinking of " + mynumber

+ ".\nIt took you " + numberofguesses+ " guess" + (numberofguesses == 1 ? "" : "es" )+ " to find out." ,"Correct guess!" );

System.exit(0);}

} 8

Page 9: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

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 verifythe behaviour of object identity that you expect.

When two objects are created with two calls to new, they exist separately in the computersmemory. So changing one object does not affect the other.

b) Experiment with SpecialDate objects, and setting names for them. When youcreate a special date for the first time, how is the underlying date created?

The underlying date is created with the Date() constructor, so it is given the default dateof 14th October 2002, just as other new Date objects. This is because Java calls theconstructor for the super class when the SpecialDate() constructor is invoked.

c) Experiment with Holiday objects. Create a single-day holiday maydayholiday forMay 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.

This is a case where we have an alias: two different names for the same object. Bothmaydayholiday.start and maydayholiday.end will hold mayday . So if we change theyear of the mayday date to next year, both fields of maydayholiday reflect the change.

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) {

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 on10/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.

9

Page 10: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

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. Addanother method which returns the dog’s age in years. (You’ll need to check themethods 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.

We modify Dog by overloading the constructor and adding an accessor method. Note that Doghas been replaced with Dog2 everywhere in the solution.

� �import java.util.GregorianCalendar;import java.text.SimpleDateFormat;

public class Dog2 {String name;GregorianCalendar birthday;SimpleDateFormat sdf = new SimpleDateFormat();/* constructor to make a new dog born today */public Dog2(String n) {

name = n;birthday = new GregorianCalendar();

}/* constructor to make a new dog, born on date b */public Dog2(String n, GregorianCalendar b) {

name = n;birthday = b;

}public String getName() {

return name;}public String getBirthday() {

return sdf.format(birthday.getTime());}public int getAge() {

GregorianCalendar today = new GregorianCalendar();return today.get(GregorianCalendar.YEAR) -

birthday.get(GregorianCalendar.YEAR);}

} 10

Page 11: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

� �import java.util.GregorianCalendar;public class MyDog {

public static void main(String[] args) {Dog2 dog = new Dog2(args[0],

new GregorianCalendar(1978,6,7));

System.out.println(dog.getName() + " was born on "+ dog.getBirthday() + "." );

System.out.println( "Therefore " +dog.getName()+ " is "+ dog.getAge() + " years old." );

}}

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 notbe able to pick up dogs that haven’t been dropped off yet. Write a program MyKennelwhich tests the Kennel class, by making a kennel, putting some dogs into it, showingthe 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 howthis class works, only how to use it.

� �// Kennel.java: a container for Dogs

import java.util.Hashtable;

public class Kennel{Hashtable h = new Hashtable();

// We use Strings as keys in the Hashtable,// so dogs in the Kennel must have unique names.public void dropOff(Dog doggie) {

h.put(doggie.getName(),doggie);}public Dog pickUp(String name) {

Dog doggie = (Dog) h.get(name);h.remove(name);return doggie;

}public String toString() {

return h.toString();}

} 11

Page 12: Simple Java Programs - University of EdinburghSchool of Informatics, University of Edinburgh Computer Science 1 Ah CS1Ah Solution Sheet 1 Simple Java Programs This is a solution set

School of Informatics, University of Edinburgh Computer Science 1 Ah

� �// MyKennel.java: a test Kennel.

public class MyKennel {public static void main(String[] args) {

Kennel mykennel = new Kennel();

Dog rover = new Dog( "Rover" );Dog spot = new Dog( "Spot" );

mykennel.dropOff(rover);mykennel.dropOff(spot);

// Show the Kennel with a couple of dogsSystem.out.println(mykennel.toString());

// Try to get Rover back.Dog rover2 = mykennel.pickUp( "Rover" );

if (rover2 == rover) {System.out.println( "I got Rover back!" );

} else {System.out.println( "I lost Rover!" );

}System.out.println(mykennel.toString());

}}

10. Read through the early chapters of your Java textbook, which cover the materialthat 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/11/27 17:39:22.

12