MSc in Computer Science SE510 Exercise 1: Getting started with Java programming The purpose of this exercise is to give you the first taste of writing programs using the Java Development Kit (JDK). You will see how to write a program, compile it, and run it, i.e. everything that programming really amounts to. The exercise has been organised as a progressing series of problems. You are provided with explanatory solutions to the first few of them, but the remaining problems, as well as everything in the future exercises, will be left for you to tackle. If you are stuck at any point don’t be afraid to ask for help, but before you do that, please make sure you have exhausted all possibilities. Problem 1. Set up your default login Edit the file .login in your home directory to include the line: source /bham/global/Java11Login after the line #source /bham/global/EmacsLogin Do this by: 1. Open a text editor, e.g. xemacs, by typing the following command in the command line window: > xemacs & 2. Open the file by selecting Open File from the Files menu and enter .login at the bottom of the emacs window (~/.login). 3. Save the file (select Save Buffer from the Files menu). 4. Exit xemacs Problem 2. Create and run a program that prints “Hello World” Solution: 1. Create program source file 1. Open a text editor, e.g. xemacs, by typing the following command in the command line window: > xemacs & 2. In the editor type the following program into the file or simply copy it from a pretyped one. In order to do that choose Insert File from the Files menu and enter this line at the bottom of the emacs window (remember to delete any default characters that xemacs will put there for you). /home/pg/mcc/projects/java/HelloWorld.java class HelloWorld { public static void main(String[] arguments) { System.out.println("Hello World!"); } } 3. When you have created your program file, you need to save it to your directory. You should have a separate directory for your Java programs, so that they are not confused with other files that you will create in the future. To create such a directory, in the command line window enter, e.g. the following: > mkdir java Java is an example name. If you wish to call your directory any other name (e.g. programs, projects, or workshop), feel free to do so. Now you can save your program into the directory you have just created. From the Files menu choose Save Buffer, and enter the name of the directory followed by a slash sign “/” and the name of the file. The file name has to be the same as the name of the main class of your program, i.e. “HelloWorld”, with the suffix “.java”. It is important that the case of the letters in the file name is exactly the same as in the class name. Therefore, what you enter will look something like this: ~/java/HelloWorld.java where “~” is an abbreviation representing your home directory. 2. Compile the source file In the command line window, move to your java program directory in order to have direct access to your HelloWorld program file. Use the following command: > cd java or any other directory name you have chosen in step 2.1.3. Now run the Java compiler on HelloWorld program file in order to produce code which is understandable to the computer: > javac HelloWorld.java If no errors come up, a file called “HelloWorld.class” should appear in the directory where “HelloWorld.java” is. You can check it by entering the command: > ls which lists the contents of the current directory. 3. Run the compiled program In the command line window enter the command: > java HelloWorld The program should respond by printing “Hello World!” in the line below the command. Problem 3. Change the program to display your name instead of “World” Solution: Come back to the editor window, which should still contain your source program file. In the line System.out.println("Hello World!"); replace “World” with your name. Then save the file by choosing Save Buffer from the Files menu, and carry out steps 2.2 and 2.3 again. Problem 4. Change the program to display your name 10 times in separate lines Solution: Again in the editor, before the line System.out.println("Hello John!"); insert a new line containing the following loop statement for (int i = 0; i < 10; i++) Indent the “System.out... etc.” line by a few space characters, to emphasise that it is nested within a loop. Save the file and then compile and run it. Problem 5. Change the program to display your name 10 times, but this time each line should be indented as shown below Hello John! Hello John! ... Hello John! Solution: Expand the statement within the loop into a block which includes printing extra spaces in front of every new line. There should be i spaces in front of the i’th line. We can generate them by using another loop that iterates from 0 to i, where i is the number of the current line, produced be the main loop. The following two lines do the job: for (int j = 0; j < i; j++) System.out.print(‘ ‘); They need to be inserted before the “System.out... etc.” line in your program, but keep in mind that, since now we are executing more than one statement in the main loop, we must embrace them with a pair of curly brackets, as shown in the skeleton code below: for (...) { statement1 ... statementn } Compile the code and see if it works. Problem 6. Change the program so that it asks for a name and the number of times it is to be displayed Solution: At the beginning of the file, insert the following line import java.io.*; This will import a useful input/output package that we are going to use. Next, before the main loop statement, insert a line that prompts the user for a name, e.g. System.out.print(“Please enter your name: “); Declare a string variable that will store the name entered by the user (put this line at the start of the function) String name; and create an input reader that will bring this name into your program BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Now insert a statement that will extract the name from the reader, and place it in the “name” variable. str = reader.readLine(); Next, insert similar code to get the number of iterations from the user System.out.print(“Please enter number of iterations: “); int number = Integer.parseInt(reader.readLine()); Note, that we have reused the input reader from above and initialised the number variable with the data read from the input. However, we had to convert the string extracted from the reader into an integer number, using the Integer.parseInt() method. In order for the user data to have effect we have to use the “name” and “number” variables instead of the constant values in our program. To do that, replace “10” in the statement for (int i = 0; i < 10; i++) with “number”, and change the line System.out.println("Hello John!"); to System.out.println("Hello " + name + ‘!‘); Try compiling and running the program. If you have problems, compare it with the original version at /home/pg/mcc/projects/java/HelloWorld1.java You can view it by selecting Open File from the Files menu and entering the above path. Problem 7. Check if the following program is correct. If not, correct the mistakes and run it. class Count { public static void main(String[] arguments) { while (System.in.read() != ‘\n‘) count++; System.out.println("Input has " + count + " characters.") } } Solution: over to you Problem 8. Write a program called Diamond that generates the following pattern * *** ***** *** * Solution: over to you Hint: see next problem Problem 9. Explore the course web pages at http://www/~rjh/courses/msc/. Find a hint to solving the previous problem Run Netscape by entering the command: > netscape & Problem 10. Print the program written in 8 and its output on a printer. Send the program file to printer lw1 using the command > lpr -Plw1 Diamond.java In order to print the output of your program, direct it to a file, like this > java Diamond > anyfile.txt Then send it to the printer as before > lpr -Plw1 anyfile.txt Problem 11. Email the program generated in 8 to another student In Netscape choose New Mail Message from the File menu. In the Message Composition window enter the recipient’s address, and copy your program into the message body (you can use Cut & Paste). Alternatively, include your program file as an attachment. Problem 12. Post a message to the cs.courses.msc newsgroup introducing yourself In Netscape choose Open Location from the File menu and enter cs.courses.msc. In the news window that will appear choose New Message from the File menu. In the Compose window type in your message. Problem 13. Show your work to one of the lab. supervisors Get one of the lab. supervisors to look at what you have done. They may suggest some changes or extensions. I walk them through file creation process to give them an idea of program writing. BTW, will they know UNIX commands from elsewhere, and what text editor shall we use? I assumed emacs for the time being. What about source’ing Java11Login? What do you think of the idea? You mentioned you would have something to suggest to them.