Introduction to Programming Lab Work. Michael Charleston. May 20, 2014

Size: px
Start display at page:

Download "Introduction to Programming Lab Work. Michael Charleston. michael.charleston@sydney.edu.au. May 20, 2014"

Transcription

1 Introduction to Programming Lab Work Contents Michael Charleston May 20, Lab work Lab 1 : Hello, World! and the Terminal Lab 2 : Variables and Eclipse Lab 3 : More sophisticated programming with if/else and Boolean logic Lab 4 : Switch, iteration and methods Lab 5 : Arrays, Iteration and a Barrel of Monkeys Lab 6 : Quiz, Classes and Objects Lab 7 : Writing Classes and Using Arrays Lab 8 : Interfaces and Collections Lab 9 : File I/O and Exceptions Lab 10 : More Inheritance Lab 11 : Testing

2 Introduction to Programming Course Notes INFO110 1 Lab work 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.

3 Introduction to Programming Course Notes INFO 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 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 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: 1 public class HelloWorld { 2 public static void main ( String [] args ) { 3 System. out. println (" Hello, World!"); 4 } 5 } 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 > 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.

4 Introduction to Programming Course Notes INFO110 > javac Box.java > java Box 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: > java PrintName \ / / / \/ / / / \ +--+ \ / \ \ \ \ \ \ \ 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 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 public static void main ( String [] args ) { 6 System. out. println (" Hello "); 7 System. out. println (" I will add two numbers for you "); 8 System. out. println (" Enter two whole numbers on one line "); 9 int n1, n2; // <-- this is saying we ' ll have two integers 10 Scanner keyboard = new Scanner ( System. in ); 11 // The statement above lets us read input from the keyboard.

5 Introduction to Programming Course Notes INFO n1 = keyboard. nextint (); // reads the first number 13 n2 = keyboard. nextint (); // reads the next number 14 System. out. println (" The sum of your numbers is:"); 15 System. out. println (n1+n2 ); 16 keyboard. close (); 17 } } Compile the program using the javac command. You might have to change some things to make it compile correctly without any errors. 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. Homework: Read this brilliant commentary on how NOT to go about a programming assignment!

6 Introduction to Programming Course Notes INFO110 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: 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 1 System. out. println (" "); 2 System. out. println (" "); 3 System. out. println (" "); 4 System. out. println (" "); 5 System. out. println (" "); The complete program looks like this: 1 public class Box { 2 public static void main ( String [] args ) { 3 System. out. println (" "); 4 System. out. println (" "); 5 System. out. println (" "); 6 System. out. println (" "); 7 System. out. println (" "); 8 } 9 } 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 = " ";

7 Introduction to Programming Course Notes INFO110 and finally print out all the box by printing out the Strings one after the other: 1 String top = " "; 2 String sides = " "; 3 System. out. println ( top ); 4 System. out. println ( sides ); 5 System. out. println ( sides ); 6 System. out. println ( sides ); 7 System. out. println ( top ); Extension Solutions 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: 1 System. out. println (" "); 2 System. out. println (" \ /"); 3 System. out. println (" \ /"); 4 System. out. println (" \ /"); 5 System. out. println (" \/");... 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 1 public class Triangle { 2 public static void main ( String [] args ) { 3 System. out. println (" "); 4 System. out. println (" \ /"); 5 System. out. println (" \ /"); 6 System. out. println (" \ /"); 7 System. out. println (" \/"); 8 } 9 } will give ~> 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 \

8 Introduction to Programming Course Notes INFO110 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: 1 public class Triangle { 2 public static void main ( String [] args ) { 3 System. out. println (" "); 4 System. out. println (" \\ /"); 5 System. out. println (" \\ /"); 6 System. out. println (" \\ /"); 7 System. out. println (" \\/ "); 8 } 9 } 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 \ / \ / \ / \/ ~>

9 Introduction to Programming Course Notes INFO 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 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 1 let x be an integer 2 let y be an floating-point number 3 x 2 // What does x equal? 4 x x + 3 // What does x equal? 5 y 1/x 1 // What does y equal? 6 x 150y // What does x equal? 7 y x + y // 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. 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.

10 Introduction to Programming Course Notes 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... Exercise 6 (approx. 20 minutes) : Change the view in Eclipse to Debug mode. Debugging is ahugely 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 you should see a button with a picture of a bug on it click and hold that, and on the drop-down 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. You can run your code with the Resume button that looks like a Pause/Play button for a CD player (on my Mac this is equivalent to pressing the F5 button). Your code should stop executing at the breakpoint you set. Now click the step over button (F6 on my Mac) and you should see the 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:

11 Introduction to Programming Course Notes INFO110 Underweight B M I 18.5 Normal weight B M I = Overweight B M I = 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... 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: ISPRIME (n) 1 if (n 1) then 2 print "not prime" 3 return 4 for (i = 2 up to n) do 5 if (i is a factor of n) then 6 print "not prime: i is a factor" // where i is the factor 7 return 8 print "n is prime" // where n is the number and remember that the command to run the compiled program is java IsPrime 45 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: 1 String numberasstring = " 12"; 2 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 Solution 1.1.

12 Introduction to Programming Course Notes INFO110 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: 1 package lab02 ; 2 3 import java. io. PrintStream ; 4 5 public class Variables { 6 7 public static void main ( String [] args ) { 8 int x = 2; 9 x = x + 3; // or x += 3 10 System. out. println ("x = " + x); 11 int y = x -1; 12 System. out. println ("x = " + x + " and y = " + y); 13 x = y; 14 System. out. println ("x = " + x + " and y = " + y); 15 y = y + x; // or y = x + y; 16 System. out. println ("x = " + x + " and y = " + y); 17 } 18 } which would give you the correct answers: x = 5 x = 5 and y = 4 x = 4 and y = 4 x = 4 and y = 8 Exercise 6 on printing out the first 25 odd numbers requires you to use a loop: 1 package lab02 ; 2 3 public class Odds { 4 5 public static void main ( String [] args ) { 6 for ( int i = 0; i < 25; i ++) { 7 System. out. println (2* i +1); 8 // this is the really easy way! 9 } 10 } 11 } In pseudocode it s just like this: Algorithm 3: ODDS 1 for (i in the range 1 to 25) do 2 print 2i+1 Running it in from within Eclipse we just get this:

13 Introduction to Programming Course Notes INFO as desired. We could have written that loop in several different ways, including these two: 1 for ( int i = 1; i < 50; i += 2) { 2 System. out. println (i); 3 } 1 for ( int i = 0; i < 50; i ++) { 2 if (i % 2 == 1) { 3 System. out. println (i); 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! 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: PRIMES 1 for (n in the range 2,..., 1000) do 2 if (n is prime) then 3 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 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: PRIMES 1 for (n in the range 2,..., 1000) do 2 for (k < n) do 3 if (n%k = 0) then 4 n can t be prime so don t print it 5 if (n is prime) then

14 Introduction to Programming Course Notes INFO110 6 print n 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 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 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: PRIMES 1 for (n in the range 2,..., 1000) do 2 for (k < n) do 3 if (n%k = 0) then 4 n can t be prime so don t print it 5 if (n is prime) then 6 print n we re ready to code: 1 package lab02 ; 2 3 public class Primes { 4 5 public static void main ( String [] args ) { 6 for ( int n = 2; n < 1000; n ++) { 7 boolean prime = true ; 8 for ( int k = 2; k* k < n; k ++) { // tests to see if k < sqrt ( n) 9 if (n % k == 0) { 10 // n can 't be prime 11 prime = false ; 12 } 13 } 14 if ( prime ) { 15 System. out. println (n); 16 } 17 } 18 } 19 } 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 public static void main ( String [] args ) { 6 for ( int n = 2; n < 1000; n ++) { 7 boolean prime = true ; 8 for ( int k = 2; k* k < n; k ++) { 9 if (n % k == 0) { 10 // n can 't be prime 11 prime = false ; 12 break ; 13 } 14 }

15 Introduction to Programming Course Notes INFO if ( prime ) { 16 System. out. println (n); 17 } 18 } 19 } 20 } We ll learn more about the break keyword next week. Extension 2 This is a more complex question, but only by a little.

16 Introduction to Programming Course Notes INFO 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: 1 int x = 20; 2 int y = 4; 3 if (x % y == 0) { 4 System. out. println ( y + " is a factor of " + x); 5 } 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. 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 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. 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) : compile and run in Eclipse. Download the NumberCrunch program skeleton code and get it to 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.

17 Introduction to Programming Course Notes INFO110 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. 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: 1 public static void printreciprocal ( int a) { 2 //... your code here 3 } 1 public static void printproductandrelationship ( int a, int b) { 2 //... your code here 3 } 1 public static void printmax ( int a, int b, int c) { 2 //... your code here 3 } 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: 1 if ( args. length == 2) { 2 printproductandrelationship (a, b); 3 // assuming you already had got values for a and b 4 } 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!

18 Introduction to Programming Course Notes INFO 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 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. Don t do the quiz now, but feel free to discuss it with your class mates when you get the chance. 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. debugger 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

19 Introduction to Programming Course Notes INFO110 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: switch iteration 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. 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: > java WordScore ZA You score 11 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: 1 String s = " HELLO "; 2 String lower = s. tolowercase (); // now lower = " hello " 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: 1 switch (ch) { 2 case 'a': case 'e': case 'i': case 'o': case 'u': 3 System. out. println (" character " + ch + " is a vowel."); 4 break ; 5 } (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.

20 Introduction to Programming Course Notes INFO110 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: Algorithm 7: PRINTFACTORS (n) 1 let n be a positive integer 2 if (n < 1) then 3 print this has no factors of interest 4 return 5 let i be an integer 6 i n 7 while (i > 0) do 8 if (i is a factor of n) then 9 print i 10 i i 1 11 print "All done." 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: 1 public static boolean isafactor ( int n, int f) 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.

21 Introduction to Programming Course Notes INFO 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. 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. 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: 1 public static void main ( String [] args ) { 2 /* 3 First, check the first argument to see if it 's " triangle ", 4 " rectangle " or " diamond ". 5 If it 's " triangle " then 6 Parse the next argument as an int, which will be the size. 7 Draw a triangle by calling the drawtriangle method and giving it 8 the size. 9 Otherwise, if it 's " rectangle " then 10 Parse the next two arguments as ints, which will be the height 11 and width. 12 Draw a rectangle by calling the drawrectangle method and giving 13 the dimensions. 14 Otherwise, if it 's " diamond " then 15 Parse the next argument as an int, which will be the size. 16 Draw a diamond by calling the drawdiamond method and giving it 17 the size. 18 Otherwise, 19 Print " I do not recognise that shape " 20 */ 21 }

22 Introduction to Programming Course Notes INFO110 Your code will have different methods though, like this: 1 public static double getaverage ( int [] numbers ) { 2 // TODO manually generated useless comment 3 } 4 5 public static int getmin ( int [] numbers ) { 6 // TODO manually generated useless comment 7 } 8 9 public static int getmax ( int [] numbers ) { 10 // TODO manually generated useless comment 11 } 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. 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: 1 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 You entered 5 numbers in the range [1, 12]. Their average value is 4.4. Of course until you fill in your methods your output won t be as helpful, probably like this: > java Stats 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.

23 Introduction to Programming Course Notes INFO110 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: GETMAXIMUM (A) 1 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) 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: 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 // where n is the length of the array 6 return(mean) 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! 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: 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:

24 Introduction to Programming Course Notes INFO110 Algorithm 10: BOGOSORT (A) 1 given A, a set of numbers 2 while (A is not in order) do 3 randomise the order of A 4 return(a) 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: Algorithm 11: PONGOSORT (A) 1 given A, a set of numbers 2 while (A is not in order) do 3 randomise the values in A 4 return(a) 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: 1 public static boolean inorder ( int [] numbers ) { 2 if ( numbers. length < 2) { 3 return true ; 4 } 5 for ( int i = 1; i < numbers. length ; ++ i) { 6 if ( numbers [i -1] > numbers [i]) { 7 return false ; 8 } 9 } 10 return true ; 11 } 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);

25 Introduction to Programming Course Notes INFO 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 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: 1 package lab06 ; 2 3 public class Blobs { 4 5 public static void main ( String [] args ) { 6 BufferedImage image = new BufferedImage (100, 100, 7 BufferedImage. TYPE_ INT_ RGB ); 8 for ( int i = 0; i < 100; ++ i) { 9 for ( int j = 0; j < 100; ++ j) { 10 image. setrgb (i, j, ( int ) ( Math. random () * 0 xffffff )); 11 } 12 } 13 File outputfile = new File (" random. png "); 14 ImageIO. write ( image, " png ", outputfile ); 15 } 16 } 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 int rgb = ( int ) ( Math. random () * 0 xffffff ); 2 rgb &= 0 x00ff00 ;... and then use image.setrgb with your new masked value of rgb.

26 Introduction to Programming Course Notes INFO110 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 ı 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: 1 public static void main ( String [] args ) { 2 Complex c = new Complex (); 3 c. real = 1.1; 4 c. imaginary = 2.0; 5 System. out. println (c. getmagnitude ()); 6 } 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: c = r eal 2 + i mag i nar y 2

27 Introduction to Programming Course Notes INFO 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 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 } 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. 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. 1 public class Rectangle { 2 private int rgb ; 3 private int xcoord ; 4 private int ycoord ; 5 private int width ; 6 private int height ; 7 public Rectangle ( int x, int y, int w, int h, int col ) { 8 // store the coordinates of the rectangle, the width and height, 9 // and the rgb colour 10 } 11 public void draw ( BufferedImage image ) { 12 // Write a nested loop to draw this rectangle in the image provided. 13 // Take care not to go outside the image! 14 } 15 } 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:

28 Introduction to Programming Course Notes INFO110 1 int size = 500; // the image will be a square 2 BufferedImage image = new BufferedImage ( size, size, 3 BufferedImage. TYPE_ INT_ RGB ); // as in previous lab 4 int numrects = 20; 5 Rectangle [] rect = new Rectangle [ numrects ]; 6 for ( int i = 0; i < numrects ; ++ i) { 7 // set random coordinates for the rectangle 8 int x = ( int ) ( Math. random () * size ); 9 int y = ( int ) ( Math. random () * size ); 10 rect [i] = new Rectangle (x, y, 20, 20, 11 ( int ) ( Math. random () * 0 xffffff )); 12 } 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: 1 for ( Rectangle r : rect ) { 2 r. draw ( image ); 3 } 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: 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).

29 Introduction to Programming Course Notes INFO110 Use the following IntPair class as a guide: 1 public class IntPair { 2 private int x; 3 private int y; 4 public IntPair ( int a, int b) { 5 x = a; 6 y = b; 7 } 8 public String tostring () { 9 String str = "(" + x + ", " + y + ")"; 10 return str ; 11 } 12 public boolean equals ( IntPair ip) { 13 boolean same = false ; 14 if (( ip. x == x && ip. y == y) // same and in order 15 (ip.x == y && ip.y == x)) { // reverse order 16 same = true ; 17 } 18 return same ; 19 } 20 } 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: 1 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, 1 System. out. println (bw ); 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

30 Introduction to Programming Course Notes INFO110 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. 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): > javac mock/words.java > java mock/words Twas brillig and the slithy toves 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: > javac mock/triangle.java > java mock/triangle 5 + / / / / /

31 Introduction to Programming Course Notes INFO 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: 1 public interface Printable { 2 public void print (); // prints the object to the console 3 } 1 public class Complex implements Printable { 2 private double im; 3 private double re; 4 public Complex ( double x, double y) { 5 re = x; 6 im = y; 7 } 9 public void print () { 10 System. out. print ("(" + re + "," + im + "i)"); 11 } } 1 public class Message implements Printable { 2 private String msg ; 3 public Message ( String s) { 4 msg = s; 5 } 7 public void print () { 8 System. out. print ( msg ); 9 } 10 } 1 public static void main ( String [] args ) { 2 Printable message = new Message (" Hello, World!"); 3 Printable complex = new Complex (1.1, 0.4); 4 message. print (); 5 System. out. println (); 6 complex. print (); 7 System. out. println (); 8 } 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:

32 Introduction to Programming Course Notes INFO110 1 public interface Evaluable { 2 public double eval (); // evaluates and returns some value 3 } 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: 1 public class Lab08 { 2 public static void main ( String [] args ) { 3 Evaluable msg = new Message (" Hello!"); 4 Evaluable x = new PairOfNumbers (1.999, 2); 5 } 6 } 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. 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: 1 ArrayList < String > names = new ArrayList < String >(); 2 ArrayList < Integer > values = new ArrayList < Integer >(); 3 ArrayList < Position > places = new ArrayList < Position >(); 4 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 public static void main ( String [] args ) { 2 Evaluable m = new Foobar (" Boo!"); 3 Evaluable q = new Barfu (3.2, m. eval ()); 4 ArrayList < Evaluable > evals = new ArrayList < Evaluable >(); 5 evals. add (m); 6 evals. add (q); 7 double sum = 0.0; 8 for ( Evaluable e : evals ) { 9 sum += e. eval (); 10 } 11 System. out. println ( sum ); 12 }

33 Introduction to Programming Course Notes INFO110 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. 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: 1 public interface Edible { 2 public double getcarbohydratecontent (); 3 public double getproteincontent (); 4 } 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): 1 public class Apple implements Edible { 2 public double getcarbohydratecontent () { 3 return 0.14; // estimated ; data from http :// nutritiondata. self. com / 4 } 5 public double getproteincontent () { 6 return 0.0; 7 } 8 } 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 ArrayList < Edible > meal = new ArrayList < Edible >(); 2 meal. add ( new Apple ()); 3 meal. add ( new BaconSlice ()); 4 meal. add ( new LettuceLeaf ()); 5 meal. add ( new Tomato ()); 6 double proteincontent = 0.0; 7 double carbcontent = 0.0; 8 for ( Edible morsel : meal ) { 9 proteincontent += morsel. getproteincontent (); 10 carbcontent += morsel. getcarbohydratecontent (); 11 } 12 // some more code to work out if this is a good meal or desperately unhealthy 13 // more code to print a report on this meal... Good? Bad? Delicious?

34 Introduction to Programming Course Notes INFO 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! 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. 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. 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

35 Introduction to Programming Course Notes INFO110 Use the following skeleton code as a basis: 1 package lab09 ; 2 3 import java. io. PrintStream ; 4 import java. util. ArrayList ; 5 6 public class SortFile { 7 8 private ArrayList < String > contents ; 9 10 public SortFile ( String filename ) { 11 // open the file called filename 12 // use a loop to go through the file line by line 13 // put each line in the ArrayList 14 } public void printinorder ( PrintStream ps) { 17 /* 18 * Print out the file to the PrintStream ps, in 19 * alphabetical order. Use a loop! 20 */ 21 } /** 24 args 25 * Read in the file, line by line, and print it out again in 26 * alphabetical order. 27 * Use a File object to access the file, and then Scanner to read in 28 * the file line by line. 29 */ /* 32 * You should add some checking to the main method below : what if 33 * there are no arguments supplied? 34 */ 35 public static void main ( String [] args ) { 36 SortFile sorter = new SortFile ( args [0]); 37 sorter. printinorder ( System. out ); 38 } }

36 Introduction to Programming Course Notes INFO110 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: 1 Scanner linescan = new Scanner ( in. nextline ()); assuming you named your original Scanner in. To use a Scanner on a file the best loop is the while loop: 1 Scanner scan = new Scanner ( new File (" infile. txt " )); 2 int numlines = 0; 3 while ( scan. hasnextline ()) { 4 String line = scan. nextline (); // reads the whole line 5 numlines ++; 6 } 7 System. out. println (" There are " + numlines 8 + " lines in the file."); 9 } (Note you would need some exception handling in the above code!) To read a single String separated by whitespace from anything else, use 1 String s = scan. next (); There are many other methods available in the Scanner class to read Integer values, Float values, etc.

37 Introduction to Programming Course Notes INFO 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... 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 Open each file 2 Scan the words from each file into a list 3 Select one word from each list at random 4 Print out the trigram in an appropriate form 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].

38 Introduction to Programming Course Notes INFO 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. Complement Is something like crazy, Eratosthenes, an engineer, blue : it is something that completes the meaning of the sentence.

39 Introduction to Programming Course Notes INFO 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 5 public class Wordscore { 6 protected ArrayList < String > words ; 7 8 public Wordscore () { 9 words = new ArrayList < String >(); 10 } 11 public Wordscore ( String... inwords ) { 12 for ( String s : inwords ) { 13 words. add (s); 14 } 15 } public int getmaxscore () { 18 int maxscore = 0; 19 for ( String s : words ) { 20 if ( getscore ( s) > maxscore ) { 21 maxscore = getscore ( s); 22 } 23 } 24 return maxscore ; 25 } public double getaveragescore () { 28 double averagescore = 0; 29 for ( String s : words ) { 30 averagescore += getscore ( s); 31 } 32 averagescore /= words. size (); 33 return averagescore ; 34 } /* 37 * This method returns the score for a word. 38 * The score of a word is the sum of the scores of each letter, and 39 * the score of a letter is 1 for A or a, 2 for B or b, 3 for C or c, 40 * up to 26 for Z or z. 41 */ 42 public static int getscore ( String w) { 43 int sum = 0; 44 String word = w. tolowercase (); 45 for ( int i = 0; i < word. length (); ++ i) { 46 sum += ( int ) word. charat (i) - 'a' + 1; 47 } 48 return sum ; 49 } /**

40 Introduction to Programming Course Notes INFO args 53 */ 54 public static void main ( String [] args ) { 55 Wordscore ws = new Wordscore (" Hello ", " World ", " how ", " are ", " you "); 56 System. out. println (ws. getaveragescore ()); 57 System. out. println (ws. getmaxscore ()); 58 } } 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). 2. Create a new package called testing and then create a new JUnit Test Suite. To do this in Eclipse, click on the right-hand side of the new class button to get the drop-down menu: which should pull up a dialog box like this: Check that the package name and all othe fields in the fialog box are correct and the and click Finish..

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

Code::Blocks Student Manual

Code::Blocks Student Manual Code::Blocks Student Manual Lawrence Goetz, Network Administrator Yedidyah Langsam, Professor and Theodore Raphan, Distinguished Professor Dept. of Computer and Information Science Brooklyn College of

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide

Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide Open Crystal Reports From the Windows Start menu choose Programs and then Crystal Reports. Creating a Blank Report Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick

More information

Hypercosm. Studio. www.hypercosm.com

Hypercosm. Studio. www.hypercosm.com Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks

More information

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc. WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25

More information

Getting Started with Excel 2008. Table of Contents

Getting Started with Excel 2008. Table of Contents Table of Contents Elements of An Excel Document... 2 Resizing and Hiding Columns and Rows... 3 Using Panes to Create Spreadsheet Headers... 3 Using the AutoFill Command... 4 Using AutoFill for Sequences...

More information

Before you can use the Duke Ambient environment to start working on your projects or

Before you can use the Duke Ambient environment to start working on your projects or Using Ambient by Duke Curious 2004 preparing the environment Before you can use the Duke Ambient environment to start working on your projects or labs, you need to make sure that all configuration settings

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

6.1. Example: A Tip Calculator 6-1

6.1. Example: A Tip Calculator 6-1 Chapter 6. Transition to Java Not all programming languages are created equal. Each is designed by its creator to achieve a particular purpose, which can range from highly focused languages designed for

More information

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project. Eclipse with Mac OSX Java developers have quickly made Eclipse one of the most popular Java coding tools on Mac OS X. But although Eclipse is a comfortable tool to use every day once you know it, it is

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

AP Computer Science Java Mr. Clausen Program 9A, 9B

AP Computer Science Java Mr. Clausen Program 9A, 9B AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will

More information

Goal: Practice writing pseudocode and understand how pseudocode translates to real code.

Goal: Practice writing pseudocode and understand how pseudocode translates to real code. Lab 7: Pseudocode Pseudocode is code written for human understanding not a compiler. You can think of pseudocode as English code that can be understood by anyone (not just a computer scientist). Pseudocode

More information

If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C?

If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C? Problem 3 If A is divided by B the result is 2/3. If B is divided by C the result is 4/7. What is the result if A is divided by C? Suggested Questions to ask students about Problem 3 The key to this question

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

How to test and debug an ASP.NET application

How to test and debug an ASP.NET application Chapter 4 How to test and debug an ASP.NET application 113 4 How to test and debug an ASP.NET application If you ve done much programming, you know that testing and debugging are often the most difficult

More information

Week 2 Practical Objects and Turtles

Week 2 Practical Objects and Turtles Week 2 Practical Objects and Turtles Aims and Objectives Your aim in this practical is: to practise the creation and use of objects in Java By the end of this practical you should be able to: create objects

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Using Karel with Eclipse

Using Karel with Eclipse Mehran Sahami Handout #6 CS 106A September 23, 2015 Using Karel with Eclipse Based on a handout by Eric Roberts Once you have downloaded a copy of Eclipse as described in Handout #5, your next task is

More information

2 The first program: Little Crab

2 The first program: Little Crab 2 The first program: Little Crab topics: concepts: writing code: movement, turning, reacting to the screen edges source code, method call, parameter, sequence, if statement In the previous chapter, we

More information

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules IBM Operational Decision Manager Version 8 Release 5 Getting Started with Business Rules Note Before using this information and the product it supports, read the information in Notices on page 43. This

More information

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor

Vim, Emacs, and JUnit Testing. Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor Vim, Emacs, and JUnit Testing Audience: Students in CS 331 Written by: Kathleen Lockhart, CS Tutor Overview Vim and Emacs are the two code editors available within the Dijkstra environment. While both

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

How to use the Eclipse IDE for Java Application Development

How to use the Eclipse IDE for Java Application Development How to use the Eclipse IDE for Java Application Development Java application development is supported by many different tools. One of the most powerful and helpful tool is the free Eclipse IDE (IDE = Integrated

More information

Java Crash Course Part I

Java Crash Course Part I Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe skolbe@wiwi.hu-berlin.de Overview (Short) introduction to the environment Linux

More information

Dreamweaver and Fireworks MX Integration Brian Hogan

Dreamweaver and Fireworks MX Integration Brian Hogan Dreamweaver and Fireworks MX Integration Brian Hogan This tutorial will take you through the necessary steps to create a template-based web site using Macromedia Dreamweaver and Macromedia Fireworks. The

More information

PloneSurvey User Guide (draft 3)

PloneSurvey User Guide (draft 3) - 1 - PloneSurvey User Guide (draft 3) This short document will hopefully contain enough information to allow people to begin creating simple surveys using the new Plone online survey tool. Caveat PloneSurvey

More information

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python Introduction Welcome to our Python sessions. University of Hull Department of Computer Science Wrestling with Python Week 01 Playing with Python Vsn. 1.0 Rob Miles 2013 Please follow the instructions carefully.

More information

The first program: Little Crab

The first program: Little Crab CHAPTER 2 The first program: Little Crab topics: concepts: writing code: movement, turning, reacting to the screen edges source code, method call, parameter, sequence, if-statement In the previous chapter,

More information

ios App for Mobile Website! Documentation!

ios App for Mobile Website! Documentation! ios App for Mobile Website Documentation What is IOS App for Mobile Website? IOS App for Mobile Website allows you to run any website inside it and if that website is responsive or mobile compatible, you

More information

So you want to create an Email a Friend action

So you want to create an Email a Friend action So you want to create an Email a Friend action This help file will take you through all the steps on how to create a simple and effective email a friend action. It doesn t cover the advanced features;

More information

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved.

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

Tabs3, PracticeMaster, and the pinwheel symbol ( trademarks of Software Technology, Inc. Portions copyright Microsoft Corporation

Tabs3, PracticeMaster, and the pinwheel symbol ( trademarks of Software Technology, Inc. Portions copyright Microsoft Corporation Tabs3 Trust Accounting Software Reseller/User Tutorial Version 16 for November 2011 Sample Data Copyright 1983-2013 Software Technology, Inc. 1621 Cushman Drive Lincoln, NE 68512 (402) 423-1440 http://www.tabs3.com

More information

A Tutorial on dynamic networks. By Clement Levallois, Erasmus University Rotterdam

A Tutorial on dynamic networks. By Clement Levallois, Erasmus University Rotterdam A Tutorial on dynamic networks By, Erasmus University Rotterdam V 1.0-2013 Bio notes Education in economics, management, history of science (Ph.D.) Since 2008, turned to digital methods for research. data

More information

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code

1 Introduction. 2 An Interpreter. 2.1 Handling Source Code 1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

10 Java API, Exceptions, and Collections

10 Java API, Exceptions, and Collections 10 Java API, Exceptions, and Collections Activities 1. Familiarize yourself with the Java Application Programmers Interface (API) documentation. 2. Learn the basics of writing comments in Javadoc style.

More information

0 Introduction to Data Analysis Using an Excel Spreadsheet

0 Introduction to Data Analysis Using an Excel Spreadsheet Experiment 0 Introduction to Data Analysis Using an Excel Spreadsheet I. Purpose The purpose of this introductory lab is to teach you a few basic things about how to use an EXCEL 2010 spreadsheet to do

More information

LESSON 7: IMPORTING AND VECTORIZING A BITMAP IMAGE

LESSON 7: IMPORTING AND VECTORIZING A BITMAP IMAGE LESSON 7: IMPORTING AND VECTORIZING A BITMAP IMAGE In this lesson we ll learn how to import a bitmap logo, transform it into a vector and perform some editing on the vector to clean it up. The concepts

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Java with Eclipse: Setup & Getting Started

Java with Eclipse: Setup & Getting Started Java with Eclipse: Setup & Getting Started Originals of slides and source code for examples: http://courses.coreservlets.com/course-materials/java.html Also see Java 8 tutorial: http://www.coreservlets.com/java-8-tutorial/

More information

Android: Setup Hello, World: Android Edition. due by noon ET on Wed 2/22. Ingredients.

Android: Setup Hello, World: Android Edition. due by noon ET on Wed 2/22. Ingredients. Android: Setup Hello, World: Android Edition due by noon ET on Wed 2/22 Ingredients. Android Development Tools Plugin for Eclipse Android Software Development Kit Eclipse Java Help. Help is available throughout

More information

Q N X S O F T W A R E D E V E L O P M E N T P L A T F O R M v 6. 4. 10 Steps to Developing a QNX Program Quickstart Guide

Q N X S O F T W A R E D E V E L O P M E N T P L A T F O R M v 6. 4. 10 Steps to Developing a QNX Program Quickstart Guide Q N X S O F T W A R E D E V E L O P M E N T P L A T F O R M v 6. 4 10 Steps to Developing a QNX Program Quickstart Guide 2008, QNX Software Systems GmbH & Co. KG. A Harman International Company. All rights

More information

How to develop your own app

How to develop your own app How to develop your own app It s important that everything on the hardware side and also on the software side of our Android-to-serial converter should be as simple as possible. We have the advantage that

More information

Hadoop Tutorial. General Instructions

Hadoop Tutorial. General Instructions CS246: Mining Massive Datasets Winter 2016 Hadoop Tutorial Due 11:59pm January 12, 2016 General Instructions The purpose of this tutorial is (1) to get you started with Hadoop and (2) to get you acquainted

More information

Creating Database Tables in Microsoft SQL Server

Creating Database Tables in Microsoft SQL Server Creating Database Tables in Microsoft SQL Server Microsoft SQL Server is a relational database server that stores and retrieves data for multi-user network-based applications. SQL Server databases are

More information

Introduction to Python

Introduction to Python WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language

More information

File Management Using Microsoft Windows

File Management Using Microsoft Windows File Management Using Microsoft Windows lab 2 Objectives: Upon successful completion of Lab 2, you will be able to Define the terms file and folder Understand file and memory storage capacity concepts

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

For Introduction to Java Programming, 5E By Y. Daniel Liang

For Introduction to Java Programming, 5E By Y. Daniel Liang Supplement H: NetBeans Tutorial For Introduction to Java Programming, 5E By Y. Daniel Liang This supplement covers the following topics: Getting Started with NetBeans Creating a Project Creating, Mounting,

More information

A computer running Windows Vista or Mac OS X

A computer running Windows Vista or Mac OS X lab File Management Objectives: Upon successful completion of Lab 2, you will be able to Define the terms file and folder Understand file and memory storage capacity concepts including byte, kilobyte,

More information

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders 1.00 Lecture 1 Course Overview Introduction to Java Reading for next time: Big Java: 1.1-1.7 Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

More information

Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition

Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition Appendix M: Introduction to Microsoft Visual C++ 2010 Express Edition This book may be ordered from Addison-Wesley in a value pack that includes Microsoft Visual C++ 2010 Express Edition. Visual C++ 2010

More information

#include <Gamer.h> Gamer gamer; void setup() { gamer.begin(); } void loop() {

#include <Gamer.h> Gamer gamer; void setup() { gamer.begin(); } void loop() { #include Gamer gamer; void setup() { gamer.begin(); void loop() { Gamer Keywords Inputs Board Pin Out Library Instead of trying to find out which input is plugged into which pin, you can use

More information

CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf

CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf First Name: Last Name: NetID: The purpose of this lab is to help you to better understand functions:

More information

Samsung Xchange for Mac User Guide. Winter 2013 v2.3

Samsung Xchange for Mac User Guide. Winter 2013 v2.3 Samsung Xchange for Mac User Guide Winter 2013 v2.3 Contents Welcome to Samsung Xchange IOS Desktop Client... 3 How to Install Samsung Xchange... 3 Where is it?... 4 The Dock menu... 4 The menu bar...

More information

Email Mentoring Field Guide. Last Updated On: 1/30/2013 Created by the Learning & Organizational Development and Support Teams education@score.

Email Mentoring Field Guide. Last Updated On: 1/30/2013 Created by the Learning & Organizational Development and Support Teams education@score. Email Mentoring Field Guide Last Updated On: 1/30/2013 Created by the Learning & Organizational Development and Support Teams education@score.org Contents Quick Start Guide... 3 Overview of the Email Mentoring

More information

POOSL IDE Installation Manual

POOSL IDE Installation Manual Embedded Systems Innovation by TNO POOSL IDE Installation Manual Tool version 3.4.1 16-7-2015 1 POOSL IDE Installation Manual 1 Installation... 4 1.1 Minimal system requirements... 4 1.2 Installing Eclipse...

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

IDS 561 Big data analytics Assignment 1

IDS 561 Big data analytics Assignment 1 IDS 561 Big data analytics Assignment 1 Due Midnight, October 4th, 2015 General Instructions The purpose of this tutorial is (1) to get you started with Hadoop and (2) to get you acquainted with the code

More information

Would You Like To Earn $1000 s With The Click Of A Button?

Would You Like To Earn $1000 s With The Click Of A Button? Would You Like To Earn $1000 s With The Click Of A Button? (Follow these easy step by step instructions and you will) This Version of the ebook is for all countries other than the USA. If you need the

More information

Basic ESXi Networking

Basic ESXi Networking Basic ESXi Networking About vmnics, vswitches, management and virtual machine networks In the vsphere client you can see the network diagram for your ESXi host by clicking Networking on the Configuration

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in

More information

Lab 0 (Setting up your Development Environment) Week 1

Lab 0 (Setting up your Development Environment) Week 1 ECE155: Engineering Design with Embedded Systems Winter 2013 Lab 0 (Setting up your Development Environment) Week 1 Prepared by Kirill Morozov version 1.2 1 Objectives In this lab, you ll familiarize yourself

More information

Introduction to Eclipse

Introduction to Eclipse Introduction to Eclipse Overview Eclipse Background Obtaining and Installing Eclipse Creating a Workspaces / Projects Creating Classes Compiling and Running Code Debugging Code Sampling of Features Summary

More information

Focus X2 (Mac version) Quick Start Guide

Focus X2 (Mac version) Quick Start Guide Focus X2 (Mac version) Quick Start Guide Welcome to Focus X2 Focus X2 is now used by coaches and educators in more than 60 countries and in over 30 different sports. The purpose of this document is to

More information

Getting Started in Tinkercad

Getting Started in Tinkercad Getting Started in Tinkercad By Bonnie Roskes, 3DVinci Tinkercad is a fun, easy to use, web-based 3D design application. You don t need any design experience - Tinkercad can be used by anyone. In fact,

More information

Introducing Xcode Source Control

Introducing Xcode Source Control APPENDIX A Introducing Xcode Source Control What You ll Learn in This Appendix: u The source control features offered in Xcode u The language of source control systems u How to connect to remote Subversion

More information

Website Development Komodo Editor and HTML Intro

Website Development Komodo Editor and HTML Intro Website Development Komodo Editor and HTML Intro Introduction In this Assignment we will cover: o Use of the editor that will be used for the Website Development and Javascript Programming sections of

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install

More information

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share. LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.

More information

Part 1 Foundations of object orientation

Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed

More information

Programming in Access VBA

Programming in Access VBA PART I Programming in Access VBA In this part, you will learn all about how Visual Basic for Applications (VBA) works for Access 2010. A number of new VBA features have been incorporated into the 2010

More information

An Introduction to MPLAB Integrated Development Environment

An Introduction to MPLAB Integrated Development Environment An Introduction to MPLAB Integrated Development Environment 2004 Microchip Technology Incorporated An introduction to MPLAB Integrated Development Environment Slide 1 This seminar is an introduction to

More information

Experiences with Online Programming Examinations

Experiences with Online Programming Examinations Experiences with Online Programming Examinations Monica Farrow and Peter King School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh EH14 4AS Abstract An online programming examination

More information

Primes. Name Period Number Theory

Primes. Name Period Number Theory Primes Name Period A Prime Number is a whole number whose only factors are 1 and itself. To find all of the prime numbers between 1 and 100, complete the following exercise: 1. Cross out 1 by Shading in

More information

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science I. Basic Course Information RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE CISY 105 Foundations of Computer Science A. Course Number and Title: CISY-105, Foundations of Computer Science B. New

More information

Introduction to Programming with Xojo

Introduction to Programming with Xojo Introduction to Programming with Xojo IOS ADDENDUM BY BRAD RHINE Fall 2015 Edition Copyright 2013-2015 by Xojo, Inc. This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

13 Managing Devices. Your computer is an assembly of many components from different manufacturers. LESSON OBJECTIVES

13 Managing Devices. Your computer is an assembly of many components from different manufacturers. LESSON OBJECTIVES LESSON 13 Managing Devices OBJECTIVES After completing this lesson, you will be able to: 1. Open System Properties. 2. Use Device Manager. 3. Understand hardware profiles. 4. Set performance options. Estimated

More information

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions.

Unit 1 Number Sense. In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions. Unit 1 Number Sense In this unit, students will study repeating decimals, percents, fractions, decimals, and proportions. BLM Three Types of Percent Problems (p L-34) is a summary BLM for the material

More information

How to open an account

How to open an account If you like a flutter on the horses or any other sport then I would strongly recommend Betfair to place those bets. I find it amazing the number of people still using high street bookmakers which offer

More information

Create A Collage Of Warped Photos

Create A Collage Of Warped Photos Create A Collage Of Warped Photos In this Adobe Photoshop tutorial, we re going to learn how to create a collage of warped photos. Now, don t go letting your imagination run wild here. When I say warped,

More information

CS170 Lab 11 Abstract Data Types & Objects

CS170 Lab 11 Abstract Data Types & Objects CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Desktop, Web and Mobile Testing Tutorials

Desktop, Web and Mobile Testing Tutorials Desktop, Web and Mobile Testing Tutorials * Windows and the Windows logo are trademarks of the Microsoft group of companies. 2 About the Tutorial With TestComplete, you can test applications of three major

More information

Databases in Microsoft Access David M. Marcovitz, Ph.D.

Databases in Microsoft Access David M. Marcovitz, Ph.D. Databases in Microsoft Access David M. Marcovitz, Ph.D. Introduction Schools have been using integrated programs, such as Microsoft Works and Claris/AppleWorks, for many years to fulfill word processing,

More information

PGR Computing Programming Skills

PGR Computing Programming Skills PGR Computing Programming Skills Dr. I. Hawke 2008 1 Introduction The purpose of computing is to do something faster, more efficiently and more reliably than you could as a human do it. One obvious point

More information

Introduction to Google SketchUp (Mac Version)

Introduction to Google SketchUp (Mac Version) Introduction to Google SketchUp (Mac Version) This guide is handy to read if you need some basic knowledge to get started using SketchUp. You will see how to download and install Sketchup, and learn how

More information