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
Introduction to Programming Lab Work Michael Charleston [email protected] Contents S1 May 20, 2014 20 14 1 Lab work 1.1 Lab 1 : Hello, World! and the Terminal . . . . . . . . . . . . . . . . . . . . 1.2 Lab 2 : Variables and Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . 1.3 Lab 3 : More sophisticated programming with if/else and Boolean logic 1.4 Lab 4 : Switch, iteration and methods . . . . . . . . . . . . . . . . . . . . 1.5 Lab 5 : Arrays, Iteration and a Barrel of Monkeys . . . . . . . . . . . . . . 1.6 Lab 6 : Quiz, Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . 1.7 Lab 7 : Writing Classes and Using Arrays . . . . . . . . . . . . . . . . . . 1.8 Lab 8 : Interfaces and Collections . . . . . . . . . . . . . . . . . . . . . . 1.9 Lab 9 : File I/O and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 1.10 Lab 10 : More Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.11 Lab 11 : Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 3 9 16 18 21 25 27 31 34 37 39 Introduction to Programming Course Notes 2014S1 1 Lab work 20 14 S1 The following pages detail the lab work you will do this Semester. Don’t worry that it looks a lot – it’s intended for you to work through consistently each week, and, if you do, you’ll do well. INFO110 Introduction to Programming Course Notes 2014S1 INFO110 1.1 Lab 1 : Hello, World! and the Terminal Topics covered Compiling a Java Program, terminal Aims Learn to use the terminal (a.k.a. command-line) for some simple commands, including compiling and running a program in Java Practice in lab skills S1 Exercise 1 (approx. 15 minutes) : Before you write a Hello from the computer to the world, you should introduce yourself to the class. The tutor will start things off: when it comes to your turn, say who you are, and something interesting about yourself. If you think that being a ninja crime fighter in your spare time is interesting, then do please share: just don’t expect everyone to believe you. . . Exercise 2 (approx. 3 minutes) : Log in to a PC in the lab and start up a terminal window. Change the current directory to your “U” drive using the cd command. Your tutor should be able to help you. Exercise 3 (approx. 5 minutes) : Create a directory (a.k.a. folder) in your U drive for this unit, perhaps something like “info1103”, with the command > mkdir info1103 14 Change to that directory with cd info1103 and then make another directory for your lab work. It’s best to be organized from the beginning! You should make a directory for each lab too. Exercise 4 (approx. 15 minutes) : Write out the “Hello, World!” program in a text editor. Here’s the code: 2 3 4 5 public class HelloWorld { public static void main ( String [] args ) { System . out . println ( " Hello , World ! " ); } } Notice how everything is nicely laid out? You should do that. Don’t just copy and paste this – typing is something you might need to practice! Don’t use WordPad or a word-processor like Word. You must name your file “HelloWorld.java”. If you’re really hard core you can use a command-line editor like vi, vim or emacs. vim is pretty cool. Compile it with the javac command. If there are any errors, see if you can work out what they mean and fix them. Run the program by entering 20 1 > java HelloWorld Exercise 5 (approx. 2 minutes) : Find out what version of Java is installed on your current machine. Do this by typing java -version. Fill in the Java version here: Exercise 6 (approx. 5 minutes) : Go on the internet and find the Java API. Fill in the answers below: 1. URL of the Java API: 2. API stands for: 3. The API is most useful to me for: Exercise 7 (approx. 15 minutes) : Create a program called Box.java to print out characters to draw a box on the screen. B Introduction to Programming Course Notes 2014S1 > javac Box.java > java Box +--------+ | | | | | | +--------+ S1 Extensions These are optional! Now, if you are feeling keen, you can try out the extensions below. Check with your tutor before you continue though. Extension: In fact, get it to print out a whole load of boxes. And triangles. Maybe a circle. Use the circle to calculate the value of π (actually this is harder, so unless you’re feeling adventurous you could skip this). Go wild: print your name in outlined letters. Here’s mine: +--+ +---+ | | / / | |/ / | / | \ | \ | |\ \ | | \ \ | | \ \ +--+ +--+ +--------+ | | | +-----+ | | | +--+ | +--+ | | | +-----+ | | +--------+ 14 > java PrintName +--+ +--+ +--+ | \ / | | | | \/ | | | | | | | | | | | | |\ /| | | | | | -- | | | | | | | | | | | | | | | | +--+ +--+ +--+ 20 Actually you can draw anything you like. Note: If you want to print a backslash: \ you need to do put two backslashes in a row else you’ll get strange results. Extension: Get your program to use the input String [] args that are required in the main method, to print a useful message about the input. You’ll have to • learn how to input the args variable (pass them to the HelloWorld program) • learn how to access the args variable Extension: Do exercises 1, 2 or 4 (called Programming Projects) that occur on page 41-42 of the textbook. Here they are in case you don’t have the book yet: Ex 1 Obtain a copy of the Java program shown in Listing 1.1 from page 15: 1 import java . util . Scanner ; 2 3 public class FirstProgram { 4 5 6 7 8 9 10 11 public static void main ( String [] args ) { System . out . println ( " Hello " ); System . out . println ( " I will add two numbers for you " ); System . out . println ( " Enter two whole numbers on one line " ); int n1 , n2 ; // <-- this is saying we ' ll have two integers Scanner keyboard = new Scanner ( System . in ); // The statement above lets us read input from the keyboard . INFO110 Introduction to Programming 12 13 14 15 16 } 17 Course Notes 2014S1 n1 = keyboard . nextInt (); // reads the first number n2 = keyboard . nextInt (); // reads the next number System . out . println ( " The sum of your numbers is : " ); System . out . println ( n1 + n2 ); keyboard . close (); 18 19 } Compile the program using the javac command. You might have to change some things to make it compile correctly without any errors. S1 Ex 2 Modify your program so it prints out the sum of three numbers. Compile and run it as before. Ex 4 Write a complete program that works out in which year a person’s nth birthday will occur, given the year of their birth. 20 14 Homework: Read this brilliant commentary on how NOT to go about a programming assignment! INFO110 Introduction to Programming Course Notes 2014S1 Lab 01 Selected Solutions Exercise 7 requires you to create a program in Java to draw a box on the screen like this: +-----+ | | | | +-----+ This isn’t too hard once you have the HelloWorld program already working. Instead of printing the String “Hello, World” you will print several Strings of characters like this: +-----+ | | | | +-----+ S1 Top line: Next line: A few more like this: Bottom line: So you can achieve this easily by replacing the single 1 System . out . println ( " Hello , World ! " ); with 2 3 4 5 System . out . println ( " + - - - - -+ " ); System . out . println ( " | | " ); System . out . println ( " | | " ); System . out . println ( " | | " ); System . out . println ( " + - - - - -+ " ); 14 1 The complete program looks like this: 2 3 4 5 6 7 8 9 public class Box { public static void main ( String [] args ) { System . out . println ( " + - - - - -+ " ); System . out . println ( " | | " ); System . out . println ( " | | " ); System . out . println ( " | | " ); System . out . println ( " + - - - - -+ " ); } } 20 1 Running it we get the following output: ~> javac Box.java ~> java Box +-----+ | | | | | | +-----+ ~> In fact you can use your new knowledge of variables and store the top row in a String variable, like this: 1 String top = " + - - - - -+ " ; and similarly the sides: 1 String sides = " | |"; INFO110 Introduction to Programming Course Notes 2014S1 INFO110 and finally print out all the box by printing out the Strings one after the other: String top = " + - - - - -+ " ; String sides = " | |"; System . out . println ( top ); System . out . println ( sides ); System . out . println ( sides ); System . out . println ( sides ); System . out . println ( top ); 1 2 3 4 5 6 7 Extension Solutions S1 The first extension is to print out several different shapes. The main challenge is that you will have to print forward slashes / and backward slashes (“back slashes”) \. You may have begun by just putting in forward and backward slashes in the println statements, like this: System . out . println ( " + - - - - - - - -+ " ); System . out . println ( " \ / " ); System . out . println ( " \ / " ); System . out . println ( " \ / " ); System . out . println ( " \/ " ); 1 2 3 4 5 2 3 4 5 6 7 8 9 public class Triangle { public static void main ( String [] args ) { System . out . println ( " + - - - - - - - -+ " ); System . out . println ( " \ / " ); System . out . println ( " \ / " ); System . out . println ( " \ / " ); System . out . println ( " \/ " ); } } will give 20 1 14 . . . but that will only work for the forward slashes. In Java the backslash has a special meaning: it’s used to create escape characters, like “\n” (end-of-line character) and “\t” (tab character). So if you put a “\” in a String then it will be interpreted as beginning an escape character, but if you follow it with a space the compiler will complain: compiling ~> javac Triangle.java Triangle.java:4: illegal escape character System.out.println(" \ /"); ^ Triangle.java:5: illegal escape character System.out.println(" \ /"); ^ Triangle.java:6: illegal escape character System.out.println(" \ /"); ^ Triangle.java:7: illegal escape character System.out.println(" \/"); ^ 4 errors So what’s the solution? We must escape the usual meaning of the ‘\’, and the way we do that is. . . by using a backslash, of course! So if you want to print out \ Introduction to Programming Course Notes 2014S1 you have to use 1 System . out . println ( " \\ " ); That’s right, you need to put two backslashes to create one. Your complete code to print the desired triangle above should be like this: 4 5 6 7 8 9 S1 3 public class Triangle { public static void main ( String [] args ) { System . out . println ( " + - - - - - - - -+ " ); System . out . println ( " \\ / " ); System . out . println ( " \\ / " ); System . out . println ( " \\ / " ); System . out . println ( " \\/ " ); } } See the double backslashes? They push the strings out of alignment but they work! The code compiles and runs correctly: ~> javac Triangle.java ~> java Triangle +--------+ \ / \ / \ / \/ ~> 14 2 20 1 INFO110 Introduction to Programming Course Notes 2014S1 INFO110 1.2 Lab 2 : Variables and Eclipse Topics covered Eclipse, variables, assignment Aims To write a simple program in a well established IDE to do so some simple calculations S1 Practice in IDE, pseudocode The main idea of this lab is to introduce you to the Integrated Development Environment (IDE) Eclipse, and to see how it can help you with your programming and debugging. Don’t worry if you don’t get to the extension exercises: as always, they’re just there in case tou finish everything else off with time to spare, and for more practice later if you’d like to go on to them. Exercise 1 (approx. 5 minutes) : If you need help in installing Eclipse on your own laptop, this is the time to get it. Exercise 2 (approx. 10 minutes) : What are the values of the variables below, at the places indicated? To help you work them out, “←” means “gets the value of”. Algorithm 1: VARIABLES 2 3 4 5 6 7 let x be an integer let y be an floating-point number x ←2 x ← x +3 y ← 1/x − 1 x ← 150y y ←x+y 14 1 // What does x equal? // What does x equal? // What does y equal? // What does x equal? // What does y equal? Exercise 3 (approx. 15 minutes) : Start up the IDE Eclipse on you computer. Create a Java project called “info1103-lab02”. Make sure there is a source folder: it usually appears by default, and should be called “src”. 20 Within it, create a package called lab02. Next, make a new class file in that package called HelloWorld.java. You should then have something that looks like this: Copy your HelloWorld code in to that file from where you saved it last week. Are there any errors? In this IDE and many others, syntax errors and even other compiler errors are highlighted. You can move the mouse over the error or warning image and a message should pop up to say what the problem is. Once your code is error-free, run the HelloWorld program from within Eclipse. To do that, make sure your HelloWorld.java file is selected on the left, then go to the run button . Introduction to Programming Course Notes 2014S1 INFO110 Exercise 4 (approx. 10 minutes) : Introduce a syntax error into your program. Eclipse (and most other IDEs) will alert you almost immediately where there is a syntax error, or where the compilation would fail. Write what you did below or in your workbook and then what the error message is. Exercise 5 (approx. 15 minutes) : Now create a new class called VariablesDemo, and check the box on the dialog to say you want to create a main method (you should get in to the habit of reading these dialog boxes: this is a simple exercise in finding out what to click!). Fill in code to do the calculations you worked out above and print out the answers. Be careful! You might get some unexpected results. . . hugely 20 14 S1 Exercise 6 (approx. 20 minutes) : Change the view in Eclipse to Debug mode. Debugging is a important skill. You shouldn’t have any bugs yet but your goal here is to get practice in tracing code, which is a way of stepping through a program in tiny steps — down to a line at a time — and seeing exactly what’s happening. Eclipse has a very good debugger. Make sure your program is selected on the left – the file with your main method in it. Near the top left — click and hold that, and on the drop-down you should see a button with a picture of a bug on it menu go down to “Debug as. . . ” and select “Java Application”. For your program you can use either the one that prints out the first 25 odd numbers, or the calculations you coded from the first exercise. Double-click in the margin on the left-hand side of the code window to make a break point part-way down your code. When you run the program you should see execution stop at that break point. button that looks like a “Pause/Play” button for a CD You can run your code with the “Resume” player (on my Mac this is equivalent to pressing the F5 button). Your code should stop executing at (F6 on my Mac) and you should see the the breakpoint you set. Now click the “step over” button execution has stepped down one line to the next instruction. Step through your code and look at the values of each variable you’re using: Continued on next page Exercise 7 (approx. 15 minutes) : Write a program that asks for your name (use the Listing from last week as a starting point), height in metres (m) and mass in kilograms (kg) and calculates your BMI. This is a simple formula: B M I = mass/hei g ht 2 Supposedly these are the categories that can be interpreted from the BMI: Introduction to Programming Course Notes 2014S1 INFO110 Underweight B M I ≤ 18.5 Normal weight B M I = 18.5 − 24.9 Overweight B M I = 25 − 29.9 Obese B M I ≥ 30 Although it’s well known that BMI is a terrible tool for diagnosis, it’s commonly used to gauge whether people might need to look at their diet. . . 2 3 4 5 6 7 8 if (n ≤ 1) then · print "not prime" · return for (i = 2 up to n) do · if (i is a factor of n) then · · print "not prime: i is a factor" · · return print "n is prime" 14 1 S1 Extension: Write a program to print a message to say whether an input number given is prime. A prime number is one that has just itself and the number 1 as positive integer factors. The first few primes are 2, 3, 5, 7, 11, 13, 17, 19, 23. The program should print out the first (smallest) factor that divides n. Here’s some pseudocode to help you: Algorithm 2: I S P RIME (n) // where i is the factor // where n is the number and remember that the command to run the compiled program is java IsPrime 45 1 2 20 where you fill in your own argument. NB: the above pseudocode may not work right away — you will have to look at the feedback on the testing site and fix any errors until it works. You should also use the Debug perspective to see where you might be going wrong. You will also need some way to convert an input String into an integer. This is the code snippet you should adapt for your program: String numberAsString = " 12 " ; int numberAsInt = Integer . parseInt ( numberAsString ); The code above converts the String “12” into a number, 12, and stores that value in the int variable, numberAsInt. Extension: Write a program to print out a list of all the prime numbers in the range 1 to 1000. Solution 1.1. Introduction to Programming Course Notes 2014S1 Lab 02 Solutions Exercise 1 on assignments The assignments should be very straightforward: if you have managed to understand the lectures and written a HelloWorld program you might have started by coding it as a program, like this: package lab02 ; 1 2 import java . io . PrintStream ; 3 4 public class Variables { 5 6 public static void main ( String [] args ) { int x = 2; x = x + 3; // or x += 3 System . out . println ( " x = " + x ); int y = x -1; System . out . println ( " x = " + x + " and y = " + y ); x = y; System . out . println ( " x = " + x + " and y = " + y ); y = y + x ; // or y = x + y ; System . out . println ( " x = " + x + " and y = " + y ); } 7 9 10 11 12 13 14 15 16 17 } 18 14 S1 8 which would give you the correct answers: x x x x = = = = 5 5 and y = 4 4 and y = 4 4 and y = 8 Exercise 6 on printing out the first 25 odd numbers requires you to use a loop: 20 package lab02 ; 1 2 public class Odds { 3 4 public static void main ( String [] args ) { for ( int i = 0; i < 25; i ++) { System . out . println (2* i +1); // this is the really easy way ! } } 5 6 7 8 9 10 } 11 In pseudocode it’s just like this: Algorithm 3: O DDS 1 2 for (i in the range 1 to 25) do · print 2i+1 Running it in from within Eclipse we just get this: 1 3 5 7 9 INFO110 Introduction to Programming Course Notes 2014S1 S1 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 as desired. We could have written that loop in several different ways, including these two: 2 3 for ( int i = 1; i < 50; i += 2) { System . out . println ( i ); } 1 2 for ( int i = 0; i < 50; i ++) { if ( i % 2 == 1) { System . out . println ( i ); } } 14 1 3 4 5 which are also fine, but the last one isn’t quite as efficient as it goes through a loop that is twice as long as it needs to be, and only prints out a number when it’s odd. This certainly wouldn’t work well for printing out, say, all the numbers that were multiples of 1000! 1 2 3 20 Extension 1 is to print out prime numbers. This is pretty straightforward once you remember about what is special about prime numbers, and you can use the code you wrote above for printing out the odd numbers as a guide. Here’s some pseudocode to get you going: Algorithm 4: P RIMES for (n in the range 2, . . . , 1000) do · if (n is prime) then · · print i So it just remains how to test whether the number is prime. Remember that an integer n is prime if it only has the factors n and 1 as factors. That means when we divide it by anything else, there’s some left over — a remainder. In a recent lecture you saw this operator: %, which means “modulo” or “the remainder after division by”. So 4 % 2 is 0, and 4 % 3 is 1 as 4/3 is 1 13 . Testing whether a number is even is easy: n is even if and only if n%2 is 0. So testing whether a number, say n, has x as a factor is just the same: n is something-times-k if n%k = 0. For a number to be prime, we need it to not have any factors other than itself and 1, so let’s test them all: Algorithm 5: P RIMES 1 2 3 4 5 for (n in the range 2, . . . , 1000) do · for (k < n) do · · if (n%k = 0) then · · · n can’t be prime so don’t print it · if (n is prime) then INFO110 Introduction to Programming · 6 · Course Notes 2014S1 print n for (n in the range 2, . . . , 1000) do p · for (k < n) do · · if (n%k = 0) then · · · n can’t be prime so don’t print it · if (n is prime) then · · print n 1 2 3 4 5 6 we’re ready to code: 1 package lab02 ; 2 3 public class Primes { 4 5 8 9 10 11 12 13 14 15 16 17 18 } 20 7 19 public static void main ( String [] args ) { for ( int n = 2; n < 1000; n ++) { boolean prime = true ; for ( int k = 2; k * k < n ; k ++) { // tests to see if k < sqrt ( n ) if ( n % k == 0) { // n can 't be prime prime = false ; } } if ( prime ) { System . out . println ( n ); } } } 14 6 S1 We could start coding with what we have now but let’s just make sure we’re not being inefficient here: do we really need to check all the integers less than n? No, we only need to check those integers p that are less than or equal to the square root of n. If we find a factor k that’s less than n, then we know p there’s another factor that’s bigger than n, but we just don’t care what it is. So after one more modification: Algorithm 6: P RIMES There’s one more efficiency we should really put in here though. Look at the logic above: I have a test to see if there’s a factor of n, and if there is, I set the value of prime to be false, so I know that n can’t be prime. But then instead of simply moving on to the next value of n to test, I continue to check for other factors, even though I know this n isn’t prime! Not very efficient. What makes more logical sense is to break out of the loop as soon as prime is false. This is how: 1 package lab02 ; 2 3 public class Primes { 4 5 6 7 8 9 10 11 12 13 14 public static void main ( String [] args ) { for ( int n = 2; n < 1000; n ++) { boolean prime = true ; for ( int k = 2; k * k < n ; k ++) { if ( n % k == 0) { // n can 't be prime prime = false ; break ; } } INFO110 Introduction to Programming 15 16 17 18 19 } } if ( prime ) { System . out . println ( n ); } 14 S1 We’ll learn more about the break keyword next week. Extension 2 This is a more complex question, but only by a little. 20 20 } Course Notes 2014S1 INFO110 Introduction to Programming Course Notes 2014S1 1.3 Lab 3 : More sophisticated programming with if/else and Boolean logic Practice in Dealing with mixed variable types in expressions, casting, using the if statement and if/else, practice with Boolean logic, the &&,|| and % operators There are some operators you need for this lab: % The modulus operator is a binary operator that returns the remainder when the first operand (“operand” = “thing being operated on”) is divided by the second. Here’s an example: 2 3 4 5 int x = 20; int y = 4; if ( x % y == 0) { System . out . println ( y + " is a factor of " + x ); } S1 1 The modulus operator gives the remainder when one integer is divided by another, and is often used to check whether a number is even. && This is the logical “and” operator: used to join two Boolean expressions, the resulting expression is true exactly when both the two smaller expressions are true. For example, if A is true and B is false, then A && B is false. If A and B are both true, then A && B is true. 14 || This is the logical “or” operator: used to join two Boolean expressions, the resulting expression is true if either, or both, of the two smaller expressions is true. Exercise 1 (approx. 20 minutes) : Write a program that tests to see if the integer numbers supplied at the command-line (you’ll use Integer.parseInt for this) is both even and lies in the range 20 – 200 inclusive, or is both odd and negative. For example, ‘5’ fails this test because while it’s odd, it’s not negative. 22 passes the test because it’s both even and in the right range. 20 Exercise 2 (approx. 20 minutes) : Write a program that determines whether an input integer (which you can assume is in the right format) is even — but you can’t use the modulus operator %: for this one you’ll have to use casting. The next five exercises are to fill in parts of the NumberCrunch program. You can download the skeleton for NumberCrunch from the eLearning website (Blackboard). It’s in the Code folder. These exercises are to give you experience and practice with using different number types such as float and int, and, most importantly, the use of “if” statements. If you can’t complete these all in the tutorial, try to complete them at home. Exercise 3 (approx. 5 minutes) : Download the NumberCrunch program skeleton code and get it to compile and run in Eclipse. Exercise 4 (approx. 5 minutes) : Part ‘A’ Fill in the first part of the main method, which will check to see if the number of arguments is equal to zero. You’ll have to use the variable .length after the argument args, to get its length. Look at the lecture slides if you’re not sure how. If the number of arguments is zero then the program should print out a message saying the user should enter some arguments in the form of an integer, when they run it from the command-line. Once it’s printed out that message, put return; so the main method stops and the program finishes. Exercise 5 (approx. 10 minutes) : Part ‘B’ Fill in the next part of NumberCrunch. For this part you need to deal with two integer input values. Follow the instructions in the comments. You’ll have to use an “if” statement to choose between the different behaviours, depending on the number of arguments. If there is no argument, your program should operate as described in Part ‘A’; if there is one argument, then it should operate as described in Part ‘B’. INFO110 Introduction to Programming Course Notes 2014S1 Exercise 6 (approx. 25 minutes) : Part ‘C’ Now extend NumberCrunch some more, this time to deal with two integer arguments. If two integer arguments are entered then, first, your program should print out the product of the two values. Next, it should see if one, say x, is a factor of the other, say y. y is a factor of x if, when you divide x by y, there’s no remainder. You should use the modulus operator % for this. Next, your program should do the same check the other way round: in the example above it would be to test whether x is a factor of y. S1 Exercise 7 (approx. 20 minutes) : Part ‘D’ The last addition to NumberCrunch is nice and simple: just print out the largest of the three integers. But you’re not allowed to use the Math.max method: you’ll have to use if statements. Extensions Extension: Modify your NumberCrunch program so not all the functionality is built in the main method. Write three methods, that will begin like this: 2 3 1 2 3 1 2 3 public static void printReciprocal ( int a ) { // ... your code here } public static void p r i n t P r o d u c t A n d R e l a t i o n s h i p ( int a , int b ) { // ... your code here } 14 1 public static void printMax ( int a , int b , int c ) { // ... your code here } Your new main method will call these other methods depending on whether there are 1, 2 or 3 integer numbers to deal with. For example you could do this: 2 3 4 if ( args . length == 2) { p r i n t P r o d u c t A n d R e l a t i o n s h i p (a , b ); // assuming you already had got values for a and b } 20 1 Extension: Write a program that prints all the factors of an input integer. You’ll have to use some kind of iteration — which may require you looking it up because it’s not yet been covered in the course! INFO110 Introduction to Programming Course Notes 2014S1 INFO110 1.4 Lab 4 : Switch, iteration and methods Aims Learn to use the switch statement, become familiar with the while loop and begin using the “for” loop; learn how to move code from the main method to other methods Practice in switch, String manipulation, while loops, debugger S1 Important note! Don’t worry if you can’t get through all of these exercises during your lab. You should at least aim to get through Exercises 2, 3 and 4, but if you’re struggling it may be slow. Keep working on the other exercises for practice, and don’t forget your next Task too! Exercise 1 (approx. 0 minutes) : To begin with, collect a copy of the practice quiz from your tutor. It’s not worth any marks but you’re strongly urged to complete it at home, for these reasons: • It will show you the format of your real quiz which is coming later; • It will give you practice; • It will help you understand how well you are understanding the concepts we examine you on. 14 Don’t do the quiz now, but feel free to discuss it with your class mates when you get the chance. debugger 20 Exercise 2 (approx. 5 or 20 minutes) : If you didn’t do it last week, do Extension 1 from lab 3, which asked you to move some of the code from the main method to separate methods called printReciprocal, printProductAndRelationship, and printMax, with the method signatures as described for lab 3. Remember the method signature is the triplet of method name, return type, and list of argument types. Once you’ve done that, or if you already have that done from last week, start up NumberCrunch in Debug mode in Eclipse. You might need to double-click in the margin of your main method so when you run it in the debugger it pauses. In some installations Eclipse will stop at the beginning of the main method when running in Debug mode; in others it goes right through and you won’t see what’s happening. You can change this behaviour in the preferences anyway. For the moment, you can make what’s called a break point in your code, by double clicking in the margin. A break point is somewhere that the execution of the code will stop, so you can then use the “Step” commands (small arrows near the top of your window): Step into takes you to inside the method being called; Step over takes you to the next line at the current level. Experiment with both. The next part of the exercise is to trace through what happens in your code when you run it. You will see how the different methods are called, and what variables they have, and what happens when they return. If you’re not sure what’s going on, get yout tutor to help or demonstrate. Exercise 3 (approx. 10 minutes) : Write a program that prints all the odd numbers from 1 to 99 on one line. Use a while, and then if you know how, use a for loop. while, for Introduction to Programming Course Notes 2014S1 Exercise 4 (approx. 25 minutes) : Now it’s time to get practice in writing switch statements, and we’ll do it in combination with iteration. Remember that there are some cases where you have several options of the value of a variable, and switch is the right control flow structure to use. Also remember that if you have a complex test like “is my number in the range 0, 10” then you can’t use a switch very easily. For this exercise, you need to do a little research, as well as a little programming: 1. Find out what are the letter scores for the classic game “Scrabble”. 2. Write a program that will work out the basic score of a work given as a command-line argument and print it out. > java WordScore ZA You score 11 S1 For example if you find that ‘z’ has a score of 10 and ‘a’ has a score of 1 then when you write and run your program it should look something like this: Note above that I used capital letters as my command-line arguments: your program should be able to handle upper and lower case letters without complaint or error. There’s a method you can use with Strings that will help: 2 String s = " HELLO " ; String lower = s . toLowerCase (); // now lower = " hello " 14 1 Another useful method that works on Strings is the charAt() method, which returns the char at the position provided. If the String str is "Hello" then str.charAt(1) is ‘e’. You will have to use a switch statement for the scoring. Have a case for each letter that has the same score. Yes, you’ll have to write a lot of case statements, but remember you can “stack” them like in this snippet: 2 3 4 5 switch ( ch ) { case 'a ': case 'e ': case 'i ': case 'o ': case 'u ': System . out . println ( " character " + ch + " is a vowel . " ); break ; } 20 1 (It’s not that pretty but it’s ok.) You will also have to add up the scores for each letter: make a variable called “score” to hold the total score of the word and for each letter in the word, by using a loop. Extension: If you have the time, alter your program to iterate through all the command-line arguments using a loop. You may use a while loop or any other kind of loop you know. Your program should then be able to work out the score for each word and print it. It will be easier and tidier to have a separate method that works out the score for a word, with this signature: 1 public static int getScore ( String word ) which will return the score. INFO110 switch iteration Introduction to Programming Course Notes 2014S1 Exercise 5 (approx. 25 minutes) : Write a program called Factors that accepts a positive integer argument on the command-line and then prints all the factors of that number on one line. You will possibly find this pseudocode helpful: 1 2 3 4 5 6 7 8 9 10 11 let n be a positive integer if (n < 1) then · print “this has no factors of interest” · return let i be an integer i ←n while (i > 0) do · if (i is a factor of n) then · · print i · i ← i −1 print "All done." S1 Algorithm 7: P RINT FACTORS (n) Line 8 above is to test whether i is a factor of n: for this part, write a separate method that has the following signature: public static boolean isAFactor ( int n , int f ) 14 which will return true if and only if the remainder of n when divided by f is 0. Your finished program should have both a main method and the isAFactor method. It will also use a while loop, which you can copy and adapt from the slides and your textbook. Extension: Now make it print out the factors in increasing order. You’ll have to change the initialisation of the loop (currently you set i to n: line 6 of the pseudocode), the condition to test (line 7), and the way you change i (line 10). , Now one more “actual” extension Extension: If you’re already comfortable with using while loops, use a for loop where you previously used a while loop in the exercises above. 20 1 INFO110 Introduction to Programming Course Notes 2014S1 1.5 Lab 5 : Arrays, Iteration and a Barrel of Monkeys Aims Learn how to make and use arrays, and iteration on arrays with loops. Understand when it’s appropriate to use the for each loop. S1 Practice in arrays, iteration, methods By the time you’ve finished all these exercises, your program should be able to read in a list of numbers that are supplied at the command line (not using Scanner!) and print out some statistics on them. You will write a "getAverage()" method which will return the floating point average of the set of numbers; you will write a getMaximum and a getMinimum method, which will return the largest and smallest values of the arrays supplied to them, and you’ll call the methods from the main method to create a summary report. We will do it in stages, so you can see how code can be built up gradually. This is a kind of "commentdriven programming" because you begin with comments about what your code should do, and then write the code to do the job. Before you begin, make a new project called ArraysTraining and make a package in it called stats. Inside that package make a class called Stats, with a public static void main method. 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public static void main ( String [] args ) { /* First , check the first argument to see if it 's " triangle " , " rectangle " or " diamond ". If it 's " triangle " then Parse the next argument as an int , which will be the size . Draw a triangle by calling the drawTriangle method and giving it the size . Otherwise , if it 's " rectangle " then Parse the next two arguments as ints , which will be the height and width . Draw a rectangle by calling the drawRectangle method and giving the dimensions . Otherwise , if it 's " diamond " then Parse the next argument as an int , which will be the size . Draw a diamond by calling the drawDiamond method and giving it the size . Otherwise , Print " I do not recognise that shape " */ } 20 1 14 Exercise 1 (approx. 25 minutes) : Make some skeleton code for your Stats program. You will need to fill in your main method with comments at first, saying what each method will do. For example in your Task 2 you might have done the same thing like this: INFO110 Introduction to Programming Course Notes 2014S1 Your code will have different methods though, like this: 1 2 3 public static double getAverage ( int [] numbers ) { // TODO manually generated useless comment } 4 5 6 7 public static int getMin ( int [] numbers ) { // TODO manually generated useless comment } 8 9 10 S1 11 public static int getMax ( int [] numbers ) { // TODO manually generated useless comment } To make your code compile you will have to fill in something in those methods, just to return a dummy number so the compiler will let you run the program even though it’s not yet finished. A method like this is called a "stub". Your methods should all return zero values. int minValue = getMinimum ( data ); and so on. Your code should run fine, but won’t yet give you the right answers. Don’t let that worry you though: call the methods, store their results that have been returned, and then print out a little report on the input numbers you gave it, something like this: > java Stats 1 2 3 4 12 You entered 5 numbers in the range [1, 12]. Their average value is 4.4. 20 1 14 Exercise 2 (approx. 25 minutes) : Next, fill in your main method. This part of your program will read in the command-line arguments and convert them into int values in an array. Make sure you initialise your array to be the same size as the number of arguments, and then fill in the values one by one. You will need to use a loop to iterate through the command-line arguments and then the Integer.parseInt() command to convert them to integers. Next, call the three methods listed above, and pass them your array: if you named your array "data" you would call the methods like this: Of course until you fill in your methods your output won’t be as helpful, probably like this: > java Stats 1 2 3 4 12 You entered 0 numbers in the range [0, 0]. Their average value is 0.0. but the important point here is that you have running code, even before you’ve written the complicated methods. INFO110 Introduction to Programming Course Notes 2014S1 Exercise 3 (approx. 25 minutes) : Your next job is to fill in the getMaximum method. Your tutor will explain a good logical way to get the maximum of a list of numbers if you don’t know one. To begin with though, look at this pseudocode: Algorithm 8: GET M AXIMUM (A) given A, an array of integers A 0 , ..., A (n−1) 2 let max be the first guess at a maximum 3 for (each x ∈ A) do 4 · if (x > max) then 5 · · max ← x 6 · return(x) S1 1 Exercise 4 (approx. 10 minutes) : Once you’ve done the getMaximum, getMinimum should be easy! You’ll have to change very little from your getMaximum method (once it works). Exercise 5 (approx. 20 minutes) : The last one to fill in is the getAverage method. For this you need to keep track of the total value of the numbers as you iterate through them. Here’s some pseudocode to help you: 14 Algorithm 9: GETAVERAGE (A) 1 let A be A list of numbers as before 2 let sum be 0 3 for each (x ∈ A) do 4 · sum ← sum + x 5 let mean be sum/n 6 return(mean) // where n is the length of the array You’ll have to then divide by the length of the array, and make sure you use a floating point number. You’re all done! 20 Extensions Extension: The Stats program above works out what the average, minimum and maximum value is of the input numbers. Extend it to also report which position is held by the minimum and maximum values. That is, your program should also indicate whether the maximum value is at index 0, 1, 2, 3, etc., and likewise the minimum. Extension: A magic square is a n × n array in which each integer from 1 to n 2 is present, and the sum of the elements in each row, each column and each diagonal is the same. For example, this is a magic 4 × 4 square: 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1 Write a program to test whether a given n × n array of integers is in fact a magic square. Extension: You’ve earned some play time so let’s simulate a barrel of monkeys. Have you ever heard the idea that if you get an infinite number of monkeys in front of typewriters and give them infinite time, then they must eventually (in finite time), through random tapping of keys, produce the complete works of Shakespeare? Well, now you have. We don’t have infinite time nor an infinite supply of monkeys so we’ll have to do something simpler, and introduce Pongo Sort. Pongo Sort is related to Bogo Sort, which works like this: INFO110 Introduction to Programming Course Notes 2014S1 Algorithm 10: B OGO S ORT (A) 1 2 3 4 given A, a set of numbers while (A is not in order) do · randomise the order of A return(A) Algorithm 11: P ONGO S ORT (A) 1 2 3 4 given A, a set of numbers while (A is not in order) do · randomise the values in A return(A) S1 This isn’t a great sorting method: in fact it’s often given as one of the worst possible sorting methods. But it’s a great example of a case where you can write an innocent looking program, which will eventually finish, but will take a really long time to do it. Pongo Sort works differently: as the goal is to get a list in order, the monkeys believe that any set of integers will do, so long as they’re in order. Hence, they randomly assign numbers to every position in the list, and then see if the list is in order, like this: Your task: write a PongoSort program to produce a sorted list of numbers. You’ll need a helper method to test whether the integers are in order. This will work: 3 4 5 6 7 8 9 10 11 public static boolean inOrder ( int [] numbers ) { if ( numbers . length < 2) { return true ; } for ( int i = 1; i < numbers . length ; ++ i ) { if ( numbers [i -1] > numbers [ i ]) { return false ; } } return true ; } 14 2 20 1 You will also need to write a method that randomly assigns the numbers in the array. Use the following code to get you started: 1 numbers [ i ] = ( int ) ( Math . random () * 100.0); INFO110 Introduction to Programming Course Notes 2014S1 1.6 Lab 6 : Quiz, Classes and Objects Quiz Exercise 1 (approx. 40 minutes) : First, you must follow your tutor’s instructions for doing the Quiz. If you have any questions then you should ask by raising your hand — keep the noise down! Exercises Topics covered 2D arrays, methods, classes, and constructors S1 Aims To gain practice with 2D arrays, to become familiar with the basic concepts of class and object, constructors, and how methods and variables of a class Setup Make a project called Lab06, make sure there’s a source folder in it called src, and then make a package called lab06. Put all your classes in there. Exercise 2 (approx. 30 minutes) : For this exercise you will be making an image, using the BufferedImage library. This library is useful for handling .png images. Copy the following code into a new class called RandomImage: package lab06 ; 2 3 public class Blobs { 4 public static void main ( String [] args ) { BufferedImage image = new BufferedImage (100 , 100 , BufferedImage . TYPE_INT_RGB ); for ( int i = 0; i < 100; ++ i ) { for ( int j = 0; j < 100; ++ j ) { image . setRGB (i , j , ( int ) ( Math . random () * 0 xFFFFFF )); } } File outputfile = new File ( " random . png " ); ImageIO . write ( image , " png " , outputfile ); } 5 6 7 8 9 10 11 20 12 13 14 15 16 14 1 } Get your code to compile. It won’t yet: try to work out why, and what you should do to make it compile. For example you will definitely have to import some files. When it compiles, then run your code from within Eclipse. You might immediately see a new file appear called “random.png” within the project, but if you don’t, you can refresh the project view, or locate your new file in file directory. Exercise 3 (approx. 10 minutes) : Now see what happens if you make a temporary variable of type int, that stores the result of (int) (Math.random() * 0xFFFFFF), and then modify the result. Try some of these out: what happens? • 0xFFFFFF is the biggest number possible for 6 bytes so you shouldn’t try to make it bigger, but try dividing it by 2 and see what happens to your output image. • Use a mask, on your int value, like this: 1 2 int rgb = ( int ) ( Math . random () * 0 xFFFFFF ); rgb &= 0 x00FF00 ; ... and then use image.setRGB with your new “masked” value of rgb. INFO110 Introduction to Programming Course Notes 2014S1 • Write a loop to draw a line through your image. Classes Exercise 4 (approx. 20 minutes) : Make a class called Complex which will hold a complex number. A complex number has the form r eal par t + i mag i nar y par t × ı 3 4 5 6 public static void main ( String [] args ) { Complex c = new Complex (); c . real = 1.1; c . imaginary = 2.0; System . out . println ( c . getMagnitude ()); } You will have to fill in a method in the Complex class that returns the magnitude of the number, which can be worked out with this formula: q |c| = r eal 2 + i mag i nar y 2 14 2 20 1 S1 so your Class should have two variables called “real” and “imaginary”. Make another class called “ComplexTester” which should have a main method in it. Your main method should look like this: INFO110 Introduction to Programming Course Notes 2014S1 1.7 Lab 7 : Writing Classes and Using Arrays Topics covered Creating classes, multi-class programs, and practice for the practical quiz Designing and making some classes S1 Exercise 1 (approx. 40 minutes) : To begin with we will make a class called Person. Each Person instance will have a name, a year of birth, an optional address, and an optional phone number. Each person’s date of birth will be stored as a simple int value for the year in which they were born, just to keep things simple. (The Calendar class is what you would use to store a complete address most accurately, but it’s a bit complicated to use so we’ll just stick to the year.) Part 1: make a Person class with a constructor that has a single argument, the person’s name. That means you should complete the following skeleton, ensuring that you store the name and the year of birth given: 1 public Person ( String name , int yearOfBirth ) { 2 3 } 14 Next, make a getAge method that returns the person’s age in years, ignoring the day and month of their birth, based on the current year. Finally, add methods setPhoneNumber and setAddress, which both should accept arguments of type String. Part 2: make another class file called People, with a main method. In your main method, create a few Person instances (at least 3) with different names, and different years of birth, in an array of Person objects. Write code in your main method to iterate through the Person objects to find the oldest one. Once they’re found, print the name their name, year of birth, and contact details if there are any. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 20 Exercise 2 (approx. 45 minutes) : Next we will make a new project called Shapes. In this project make a package called geometry and a class in it called Rectangle. In another package called whatever you think is sensible, make a new class called Art, with a main method. Here’s a skeleton for the Rectangle class. Note that the constructor and the method “draw” are not finished: you should finish them. public class Rectangle { private int rgb ; private int xCoord ; private int yCoord ; private int width ; private int height ; public Rectangle ( int x , int y , int w , int h , int col ) { // store the coordinates of the rectangle , the width and height , // and the rgb colour } public void draw ( BufferedImage image ) { // Write a nested loop to draw this rectangle in the image provided . // Take care not to go outside the image ! } } When you’ve filled in the above constructor and method, it’s time to move on to the main method. In the main method we will create a BufferedImage object (call it “image”) and then create several Rectangle objects, in an array, something like this: INFO110 Introduction to Programming 2 3 4 5 6 7 8 9 10 11 12 int size = 500; // the image will be a square BufferedImage image = new BufferedImage ( size , size , BufferedImage . TYPE_INT_RGB ); // as in previous lab int numRects = 20; Rectangle [] rect = new Rectangle [ numRects ]; for ( int i = 0; i < numRects ; ++ i ) { // set random coordinates for the rectangle int x = ( int ) ( Math . random () * size ); int y = ( int ) ( Math . random () * size ); rect [ i ] = new Rectangle (x , y , 20 , 20 , ( int ) ( Math . random () * 0 xFFFFFF )); } S1 1 Course Notes 2014S1 If you like, modify the code above to have Rectangles of different shapes. (Above they are all 20 by 20: you could use the same idea with Math.random() to set random dimensions.) For each Rectangle you created, call its draw method and supply the image, like this: 3 for ( Rectangle r : rect ) { r . draw ( image ); } When you run this in the debugger put a break-point on the left of the middle line above, and step into the draw method. Your method should draw on the image, and might even produce something like this: 14 2 20 1 Once you’ve mastered this, you can make all kinds of pretty pictures, by calling sequences of draw operations. Extensions Exercise 3 (approx. 25 minutes) : Write a program with two classes: one class, called Wordy, will have the main method and one will be a class for storing a pair of Strings. Call this class Bigram (a bigram is a jargon term for a pair of words). INFO110 Introduction to Programming Course Notes 2014S1 INFO110 Use the following IntPair class as a guide: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class IntPair { private int x ; private int y ; public IntPair ( int a , int b ) { x = a; y = b; } public String toString () { String str = " ( " + x + " , " + y + " ) " ; return str ; } public boolean equals ( IntPair ip ) { boolean same = false ; if (( ip . x == x && ip . y == y ) || // same and in order ( ip . x == y && ip . y == x )) { // reverse order same = true ; } return same ; } } S1 1 1 14 You can use quite a bit of the code in that class for your Bigram. The two Strings in the Bigram class should be called firstWord and secondWord. So if I construct a Bigram like this: Bigram bw = new Bigram ( " red " , " blue " ); then bw.firstWord should be "red" and bw.secondWord should be "blue". In your Wordy’s main method, construct two Bigrams and print them out. In the same main method, write code to determine which bigram has the greatest total length (the sum of the word lengths each word). Extension: Write a toString method for your Bigram class so that in the above situation, System . out . println ( bw ); 20 1 would print out ( red---blue ) Practice! Mock Practical This part of the tutorial is a “mock practical” test: it is designed to get you used to the pressured environment in which you’ll have to code correctly and quickly. It’s not worth any marks! Before you begin, make a new Java project in your workspace called info1103-mocktest. Inside it, create a package called mock. For each of the exercises below you should create a new class, with its own public static void main method (“psvm”). Here is the set of tasks you must do. For these, do not look up answers on the internet! Do not look up the answers in your book if you can avoid it! If you’re completely stuck then ask your tutor for help. The aim of this exercise is to get you ready for your real practical test later, so cheating now won’t help you. Exercise 4 (approx. 5 minutes) : Squares Introduction to Programming Course Notes 2014S1 Write a Java program to list all the square numbers between 0 and 5000 inclusive. Put your code in the main method of a class called Squares. A square number is one that is the square of an integer. You’d compile and run it like this on a terminal window: > javac mock/Squares.java > java mock/Squares or just run it from within Eclipse. The numbers should be separated by spaces. Remember, calculate the square of x by x*x, not x^2, which is the “exclusive OR” operator. S1 Exercise 5 (approx. 15 minutes) : Words Write a Java program called Words to read in words from the command-line and print out a count of how many there are of each length observed. You may assume there will be no words longer than 100 characters. Here’s how the output should look when you compile and run it from a terminal window (or put the input in as arguments in Run Configurations. . . in Eclipse): 14 > javac mock/Words.java > java mock/Words Twas brillig and the slithy toves 3 2 4 1 5 1 6 1 7 1 In the above the first column is the length of the word, and the second column is the number of words of that length. Exercise 6 (approx. 15 minutes) : Triangle Write a Java program called Triangle to draw a triangle on screen whose height is provided as arguments to the program, like this: 20 > javac mock/Triangle.java > java mock/Triangle 5 + /| / | / | / | / | +-----+ INFO110 Introduction to Programming Course Notes 2014S1 1.8 Lab 8 : Interfaces and Collections Topics covered Interfaces and a Java Collection Aims to get practice and understanding with Java interfaces, and to see how the ArrayList works Exercise 1 (approx. 25 minutes) : Interface As described in lectures we have a new reference type to learn about, the interface. Remember that an interface is a way of describing how we can interact with a class, like this example from the lecture slides: 3 1 2 3 4 5 6 7 8 9 10 11 public interface Printable { public void print (); // prints the object to the console } S1 2 public class Complex implements Printable { private double im ; private double re ; public Complex ( double x , double y ) { re = x ; im = y ; } @Override public void print () { System . out . print ( " ( " + re + " ," + im + " i ) " ); } 14 1 12 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 } public class Message implements Printable { private String msg ; public Message ( String s ) { msg = s ; } @Override public void print () { System . out . print ( msg ); } } 20 13 public static void main ( String [] args ) { Printable message = new Message ( " Hello , World ! " ); Printable complex = new Complex (1.1 , 0.4); message . print (); System . out . println (); complex . print (); System . out . println (); } yielding Hello, World! (1.1,0.4i) This week’s lab work will help you learn about this interface concept, and will show you how the idea that an variable’s static type and dynamic type can be used to do different things. First, make the following interface: INFO110 Introduction to Programming 1 2 3 Course Notes 2014S1 public interface Evaluable { public double eval (); // evaluates and returns some value } 1 2 3 4 5 6 S1 Now write two classes that implement this interface: you can choose any two kinds of class that you like (though don’t use an existing class like String!). For example, a class that has a String stored in it could return a double for the length of the String, and another class might hold two double values and return their maximum from the eval method. Next, make a main method in another class (called Lab08, say) that creates some instances of each of your classes. For the static type, with which each object is declared, use Evaluable. For the dynamic type, with which the objects are constructed, use the names of the classes you just made, like Message or PairOfNumbers or whatever you used. It will look something like this: public class Lab08 { public static void main ( String [] args ) { Evaluable msg = new Message ( " Hello ! " ); Evaluable x = new PairOfNumbers (1.999 , 2); } } 14 or similar. Don’t just use my examples – create at least one of your own! Make sure your code is running, then add a line to your main method that adds the results of two or more of your objects together: in my code above I’d add msg.eval() + x.eval(). Use the debugger to step in to the different implementations of the eval method. Your tutor will show you how if you don’t know. 1 2 3 4 20 Exercise 2 (approx. 25 minutes) : Collections Now we’re going to introduce you to another part of the Java language, the Collections Library. I’ve mentioned in class that there is something called a Set and an ArrayList, well here we’ll look at one of most commonly used, the ArrayList. Look up ArrayList in the Java API. You should find that it’s a way of storing reference types such as String or Integer, but not primitive types like int. When we make an ArrayList variable, we have to say what kind of objects will be stored in it, like this: ArrayList < String > names = new ArrayList < String >(); ArrayList < Integer > values = new ArrayList < Integer >(); ArrayList < Position > places = new ArrayList < Position >(); ArrayList < Evaluable > evals = new ArrayList < Evaluable >(); You can see above that the new interface you’ve made, Evaluable, is perfectly ok to be the type of thing being stored in the collection evals. . . Now here’s my main method, which you should use as a starting point for your own main method: 1 2 3 4 5 6 7 8 9 10 11 12 public static void main ( String [] args ) { Evaluable m = new Foobar ( " Boo ! " ); Evaluable q = new Barfu (3.2 , m . eval ()); ArrayList < Evaluable > evals = new ArrayList < Evaluable >(); evals . add ( m ); evals . add ( q ); double sum = 0.0; for ( Evaluable e : evals ) { sum += e . eval (); } System . out . println ( sum ); } INFO110 Introduction to Programming Course Notes 2014S1 To add items to an ArrayList you use the .add method. As you should recall, if you type the name of reference variable in the Eclipse IDE, then a dot ‘.’, the IDE will show you a range of methods and values that area available to you to use: there are in fact more than one .add method. Fill out the rest of your code to add your Evaluable items to your ArrayList<Evaluable> variable and then use a loop like the one above to print out the result when you sum them. Extensions If you get through all of that and have time to spare, have a go at these extension exercises. S1 Extension: Write a toString method for each of the classes that implement Evaluable. Check to see that it is called when you select a variable of that class in the debugger. Extension: Write another class that contains two Evaluable variables inside it called x and y say. Its eval method must combine the results of the eval methods called on each of x and y and return the total. This is an example of the composite design. Extension: Here’s an interface for classes of things that are Edible: 2 3 4 public interface Edible { public double get Car bo hyd ra teC ont en t (); public double getProteinContent (); } 14 1 Any class that implements the Edible interface must have these two methods filled in. For example, an Apple isn’t high in proteins but has plenty of sugar (which is a carbohydrate): 2 3 4 5 6 7 8 public class Apple implements Edible { public double get Car bo hyd ra teC ont en t () { return 0.14; // estimated ; data from http :// nutritiondata . self . com / } public double getProteinContent () { return 0.0; } } 20 1 Copy out the Edible interface and the Apple class, and then make some other classes for Edible things: for example, you might think of a sandwich of bread, bacon, tomato, and lettuce to go with the apple. Use an ArrayList<Edible> to create the perfect meal, so this code would compile and run in a main method: 1 2 3 4 5 6 7 8 9 10 11 12 13 ArrayList < Edible > meal = new ArrayList < Edible >(); meal . add ( new Apple ()); meal . add ( new BaconSlice ()); meal . add ( new LettuceLeaf ()); meal . add ( new Tomato ()); double proteinContent = 0.0; double carbContent = 0.0; for ( Edible morsel : meal ) { proteinContent += morsel . getProteinContent (); carbContent += morsel . ge tCa rb ohy dr ate Con te nt (); } // some more code to work out if this is a good meal or desperately unhealthy // more code to print a report on this meal ... Good ? Bad ? Delicious ? INFO110 Introduction to Programming Course Notes 2014S1 INFO110 1.9 Lab 9 : File I/O and Exceptions Topics covered Practical Quiz, File Input/Output, Exceptions Part 1: Practical Quiz 50 minutes, 10% of your final grade, closed book! Make sure you follow your tutors’ instructions! S1 Part 2: Lab work Aims To become familiar with opening, reading from and writing to files using Scanner and while loops, writing exception-safe file-handling. Practice in File reading using the Scanner, Exceptions, Collections.sort Setup First, make a project in your workspace in Eclipse, called info1103-lab09. Then make sure there’s a source folder called src, and create a package called lab09 in it. Your class files will go inside this package. 14 Exercise 1 (approx. 20 minutes) : Write a program using the ArrayList<String> to sort a collection of Strings in order. The Strings will be the ones received by the main method, i.e., the program arguments. You don’t have to write your own sort method this time: use Collections.sort() and pass the ArrayList as the argument. Give it these strings: “Hello”, “World”, “how”, “are”, “you”, “my”, “name”, “is”, and “Fred”. Use the enhanced “for” loop if you can, to add Strings to the ArrayList<String>, and print out the list before and after sorting. 20 Exercise 2 (approx. 25 minutes) : Write a program to read in lines from a file such as that below and print them out in alphabetical order. For example, if the input file is this: Brian curling Sylvester javelin Inga rugby Nicole running Inga running then the output file should be: Brian curling Inga rugby Inga running Nicole running Sylvester javelin see next page Introduction to Programming Course Notes 2014S1 Use the following skeleton code as a basis: 1 package lab09 ; 2 3 4 import java . io . PrintStream ; import java . util . ArrayList ; 5 6 public class SortFile { 7 private ArrayList < String > contents ; 8 9 public SortFile ( String fileName ) { // open the file called fileName // use a loop to go through the file line by line // put each line in the ArrayList } 10 11 S1 12 13 14 15 public void printInOrder ( PrintStream ps ) { /* * Print out the file to the PrintStream ps , in * alphabetical order . Use a loop ! */ } 16 17 18 19 20 21 22 /* * * @param args * Read in the file , line by line , and print it out again in * alphabetical order . * Use a File object to access the file , and then Scanner to read in * the file line by line . */ 14 23 24 25 26 27 28 29 30 32 33 34 35 36 37 38 39 40 } 20 /* * You should add some checking to the main method below : what if * there are no arguments supplied ? */ public static void main ( String [] args ) { SortFile sorter = new SortFile ( args [0]); sorter . printInOrder ( System . out ); } 31 INFO110 Introduction to Programming Course Notes 2014S1 Extensions Extension: Alter your previous program to not only sort the lines but within each line, sort the words of the line. To do this you will need to use a Scanner constructed as follows: Scanner lineScan = new Scanner ( in . nextLine ()); 1 1 2 3 4 5 6 7 8 9 } S1 assuming you named your original Scanner “in”. To use a Scanner on a file the best loop is the while loop: Scanner scan = new Scanner ( new File ( " inFile . txt " )); int numLines = 0; while ( scan . hasNextLine ()) { String line = scan . nextLine (); // reads the whole line numLines ++; } System . out . println ( " There are " + numLines + " lines in the file . " ); 14 (Note you would need some exception handling in the above code!) To read a single String separated by whitespace from anything else, use String s = scan . next (); 1 20 There are many other methods available in the Scanner class to read Integer values, Float values, etc. INFO110 Introduction to Programming Course Notes 2014S1 1.10 Lab 10 : More Inheritance Practice in inheritance, constructors, the super keyword, static and dynamic types Before you get on to more hard concept stuff, you’ve earned some fun: time to extend the Hello, World! kind of interaction with something a bit more, well, insulting: Exercise 1 (approx. 45 minutes) : The Shakespearean Insult Generator. Write a program to load words from three lists of words, and generate random tri-grams – that is, triples of three words, of the form adjective adjective noun, such as impertinent scurvy-valiant scut S1 . . . which you can include in heart-warming messages like Thou impertinent scurvy-valiant scut! The files are in the Skeleton code folder under Shakespeare. You will have to do something like the following: Insulter 1 2 3 14 4 Open each file Scan the words from each file into a list Select one word from each list at random Print out the trigram in an appropriate form 20 Exercise 2 (approx. 30 minutes) : In lectures we discussed a collection of Shape classes. One suggestion was that there could be a Shape abstract class with a single dimension (e.g., “size”), which all the other shapes would extend. Write a collection of classes with Shape as the base class and Square, Rectangle, Triangle and Circle as subclasses. Initialise them to have any dimensions (e.g., height, radius) you wish. Write a main method in a separate program that will calculate the total area of a collection of these Shapes. You may find these ingredients useful: • a Collection of some kind, to store the Shape objects; • the extends keyword; • the constant Math.PI Extension: Construct or download lists of nouns, verbs and adjectives, to construct random sentences. Some suggested simple forms are given below: 1. Subject – Verb e.g., [I] [run]. [They] [jumped]. 2. Subject – Verb – Object e..g, [We] [leapt] [the fence]. [She] [folded] [paper]. 3. Subject – Verb – Complement e.g., [Bill] [lost] [his wallet]. 4. Subject – Verb – Indirect Object – Direct Object e.g., [Stefan] [gave] [me] [his lunch]. [They] [listened to] [his radio]. INFO110 Introduction to Programming Course Notes 2014S1 5. Subject – Verb – Object – Complement e.g., [We] [mopped] [the dance floor] [gracefully]. Where Subject Is something like “I”, “They”, “Bill”: it is the main topic of the sentence. Verb Is something like “drove”, “helped”, “gave”: it is the action word or phrase. Object Is something like “a truck”, “lunch”, “cocktails”: it is a that which is being acted on. Indirect Object Is something like “her”, “us”, “me”: another object that’s being acted upon. 20 14 S1 Complement Is something like “crazy”, “Eratosthenes”, “an engineer”, “blue”: it is something that completes the meaning of the sentence. INFO110 Introduction to Programming Course Notes 2014S1 1.11 Lab 11 : Testing Topics covered Writing a Testing Suite, using JUnit Aims To learn how to write and run JUnit tests for a program, to use simple regression testing, and to understand how different execution paths can be tested. Here’s some code that you’ll use to write tests (which is available on eLearning for easy download): 1 package lab10 ; 2 3 import java . util . ArrayList ; 4 6 public class Wordscore { protected ArrayList < String > words ; S1 5 7 8 9 10 11 12 13 14 15 public Wordscore () { words = new ArrayList < String >(); } public Wordscore ( String ... inWords ) { for ( String s : inWords ) { words . add ( s ); } } 16 18 19 20 21 22 23 24 25 public int getMaxScore () { int maxScore = 0; for ( String s : words ) { if ( getScore ( s ) > maxScore ) { maxScore = getScore ( s ); } } return maxScore ; } 14 17 26 28 29 30 31 32 33 34 public double getAverageScore () { double averageScore = 0; for ( String s : words ) { averageScore += getScore ( s ); } averageScore /= words . size (); return averageScore ; } 20 27 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 /* * This method returns the score for a word . * The score of a word is the sum of the scores of each letter , and * the score of a letter is 1 for A or a , 2 for B or b , 3 for C or c , * up to 26 for Z or z . */ public static int getScore ( String w ) { int sum = 0; String word = w . toLowerCase (); for ( int i = 0; i < word . length (); ++ i ) { sum += ( int ) word . charAt ( i ) - 'a ' + 1; } return sum ; } 50 51 /* * INFO110 Introduction to Programming Course Notes 2014S1 * @param args */ public static void main ( String [] args ) { Wordscore ws = new Wordscore ( " Hello " , " World " , " how " , " are " , " you " ); System . out . println ( ws . getAverageScore ()); System . out . println ( ws . getMaxScore ()); } 52 53 54 55 56 57 58 59 } S1 There are two constructors in the above, and several methods. Your task for this week is to test this code, and make sure it’s all working correctly. There might me places where it does not run correctly, or throws an exception, or produces the right output only sometimes. For your test suite you need to do the following things: 1. Get the Wordscore code into a project in the correct package (lab10). 14 2. Create a new package called “testing” and then create a new JUnit Test Suite. To do this in Eclipse, to get the drop-down menu: click on the right-hand side of the new class button which should pull up a dialog box like this: 20 60 . Check that the package name and all othe fields in the fialog box are correct and the and click “Finish”. INFO110 Introduction to Programming Course Notes 2014S1 3. Next you need to fill in tests. Remember each test must begin with @Test and it should be called something like “testConstructor” or “testScoreMethodOne” and so on – beginning the method with “test” indicates clearly that the intention is to test something. 1 2 3 4 @Test public void testBlah () { // test something ! } 4. You may have to include JUnit 4 in the build path. The build path is where Java looks for code and libraries that it needs to run your program. 1 package lab10 ; 2 3 import static org . junit . Assert .*; 4 5 import org . junit . Test ; 6 public class WordscoreTest { 8 @Test public void test () { fail ( " Not yet implemented " ); } 9 10 11 12 13 } Exercise 1 (approx. 15 minutes) : You should begin with writing tests for the constructors of the Wordscore class. If the constructors don’t work then the rest of the class probably can’t be even tested (except for the static methods) so you should definitely do these first. There are two constructors with different lists of arguments (one takes no arguments, one takes an array of Strings or a comma-separated list of Strings), so write a test for each input. Once you’ve written the test, which can be passed just by successfully constructing Wordscore objects, you can run it. Running the JUnit test is via the Run. . . drop-down menu accessed by clicking at the right hand side of the Run button . If all goes well you should see a green bar showing your tests all passed; if any of them failed then you need to fix the code (or possible fix the test) so they pass correctly. 20 14 14 7 S1 After following these steps you should end up with something like this: Exercise 2 (approx. 30 minutes) : Now write a test or two (maybe four) for the static getScore method. Think about the types of input it could possibly receive: will the word have all letters? Will there be any strange characters? Will the word have zero length? What if I pass the method a null? There could be several different ways in which “bad” or at least unexpected input could be received by the getScore method. You should write a test for each. You might find when you’re writing and running these tests that you change the Wordscore.java code. Because it’s a good idea to use regression testing, you should do that here. Whenever you’ve made significant changes to your code you should run the old tests again to make sure that you haven’t broken anything. Only when all the tests are passed should you continue. Exercise 3 (approx. 30 minutes) : Finally, finish off with some more tests: the getAverageScore and getMaxScore methods can be tested once you know the getScore method is working correctly. Write tests for each, and again think about cases where the input might not be what you expect: null values, empty lists, etc. For these last two tests, work out what the execution paths should be for each case. For example, if you give a method a null input value, trace through what the execution should be (and you can step through it with the debugger), to make sure you write tests for each execution path. How many execution paths are there in each method / constructor? INFO110 Introduction to Programming Course Notes 2014S1 INFO110 Wordscore() Wordscore(String ... inWords) getScore(String w getAverageScore() [1] getMaxScore() S1 Extensions 20 14 If you’ve done all this then write tests for one of your previously submitted Tasks Extension: [1] don’t forget the “if”