SE15 Exercise 2

Basic Programming Examples The aims of this exercise are: 1. To gain familiarity with basic elements of the Java language. 2. To understand some simple programming ideas. 3. To develop your skills in reading and modifying Java programs. 4. To test your knowledge by means of a multiple choice quiz (and submit a certificate which shows the score you attained.)

1

Simple Programs that Print to the Screen 1. Type the following simple program into Dr Java then save, compile and run it: public class ThisPrintsSomething { public static void main( String [] args ) { System.out.println( "Something" ); } } Now alter the program so it prints the words “Something else”. 2. Type the following program into Dr Java, save it then compile and run it: public class PrintSeveralLinesExample { public static void main( String [] args ) { System.out.println( "All chocolate cakes are nice" ); System.out.println( "All my cakes are chocolate" ); } } Now modify the program so it prints a third line: “Therefore, all my cakes are nice”. Save, compile and run the modified program to check it works. Modify the program again so it prints a dashed line after the first two lines and before the conclusion. (Use a string of ‘-’ symbols to make the dashed line.)

1

3. Type the following program into Dr Java and save, compile and run it (you always do this with programs, so from now on I will assume you know this): public class PrintWordByWord { public static void main( String [] args ) { System.out.print( "All" ); System.out.print( "dragons" ); System.out.print( "breathe" ); System.out.print( "fire" ); } } Notice that the output is probably not what was intended. Modify the program to print the sentence in a more sensible way. 4. Write a program that will print your initials to in letters that are nine lines tall. Each big letter should be made up of a load of asterisk symbols, ‘*’. So my program output would look like something this: ****** ** ** ** ** ****** ** ** ** ** ** ** ** ** ******

2

****** ** ** ** ** ****** ** ** ** ** ** ** ** ** ******

Useful Operators and Methods

In this part of the exercise you will look at a number of very useful operations that you can apply to simple items of data. To test the way that Java evaluates complex code expressions, you will type these in at the Dr Java interactions pane. Note that if you type an expression into the interactions pane that does not end in ‘;’ then the expression evaluated and its value will be output. But if you add a ‘;’ at the end the expression will also be run, but the value will not be returned (you will only get output if it is actually an output command, such as System.out.println(...)).

2.1

Arithmetical Operations

One thing computers do pretty well is arithmetic. Java provides the usual numerical operations of operations of addition, subtraction, multiplication and division, denoted by the symbols +, -, * and / respectively. 1. Use the Dr Java interactions pane to evaluate the following expressions. (a) 834 * 67 (b) (2 * 3) + 4 (c) 2 * (3 + 4) 2

(d) 2 * 3 + 4 (e) 4 + 2 * 3 (f) 5 / 4 2. How does bracketing affect the way that Java evaluates an expression? What happens if there is no bracketing? (In complex expressions it is generally best to include brackets to make sure you know the order in which the various operations will be applied.) 3. Did the value of 5 / 4 come out as you expected? What might have happened? Try evaluating 5.0 / 4.0 and see what you get. This behaviour illustrates that Java makes a distinction in the way it treats whole numbers (integers of type int) and decimal numbers (floating point numbers of type float). 4. Now try to find out what the Java ‘%’ operator does. Type 5 % 3 into the interaction pane and see what you get. Repeat this with several different pairs of numbers and try to work it out. If you can’t figure it out, get the answer any way you can (Google, a text book, ask someone).

2.2

Strings

A string is a sequence of characters. In Java (as in most computer languages) strings are referred to in program code by enclosing the characters within double quotes. Examples of strings: "Hello", "This is a string", "--oOo--". 1. Using ‘+’ to Concatenate Strings There are many occasions when you will want to join two or more strings together to create a new string. This is easy to do by using the string concatenation operator ‘+’. Note that this is the same symbol as for arithmetic addition of two numbers. Java will automatically determine whether you want to do addition or concatenation by the types of expression on either side of the ‘+’ (this is a simple form of polymorphism of which you will hear more later in the course). Type "this" + "and" + "that" into the Dr Java interactions pane. What do you get?. 2. Note that, whereas in other parts of a Java program spaces are usually ignored, within a string spaces are taken seriously. Work out an expression containing exactly two strings and one + operator, such that the output will be "this string contains spaces". 3. Getting the Length of a String In Java a string is a type of object. Specifically it is an object of the class String. Like most Java classes, the String class is associated with a number of methods which enable useful operations to be carried out on it. One useful method defined for strings is ‘length()’. To apply a method to an object you use the dot operator ‘.’. Thus, one can write an expression such as ‘"a string".length()’. Try typing the following into the interactions pane of Dr Java: "Any string you want to type".length() Dr Java should respond by outputting the length of the string. 4. (Optional Advanced Part) Referring to Individual Characters within Strings. In many languages a string is simply a sequence of characters — i.e. a character array. However, as noted earlier, in Java the String type is a fully-fledged object class. To convert a String a character array you can use the method toCharArray(). This enables 3

you to access the individual characters of a string. For instance, try evaluating the expression "anti-disestablishmentarianism".toCharArray()[0]; then try substituting other numbers in place of 0 and see what you get. What is this computing?

3

Programs with Variables

A variable is a name that is used within a program to store a value. The name is chosen by the programmer and, although any name could be used, it is good practice that the name gives an indication of what type of value the name refers to. 1. (a) Type the following code into Dr Java. This declares three variables each of type int (which means that their values are integers — i.e. whole numbers). The variables are used to store scores obtained by a student in each of three subjects. The code also assigns values to each of the variables. public class ScoreAverage { public static void main( String [] args ) { System.out.println( "** Program to compute average score **"); int mathsScore = 47; int englishScore = 67; int musicScore = 88; int totalScore; // coding incomplete } } (b) Add an additional line of code that sets the value of totalScore to be the sum of the three subject scores. (This line should refer to the subject scores using the variables not directly use the score values.) Compile and run (c) Add a line of code that prints out “Total: ” followed by the value of totalScore. (d) Declare a fifth variable integer average and use an arithmetic expression to set this equal to the average of the scores. (e) Add a further line of code to display the average score. (f) Why is the average rounded down to the the whole number below the real average? (Optional: Fix this by declaring variables totalScore and average to be of type float.) 2. Enter the following program into DrJava and run it: public class IncrementationExperiment { public static void main( String [] args ) { int num = 3; ++num; System.out.println( num ); System.out.println( ++num ); System.out.println( num ); System.out.println( num-- ); System.out.println( num ); } } 4

Observe the output and try to work out the difference between the operations ++num and num++. If you can’t figure it out, look it up in a text book.

4

Looping the Loop

For this part of the exercise you will start with a simple program containing a while loop and make a number of modifications to change the behaviour of the program. Here is the initial code: // This is a simple program using a ‘while’ loop // Note: everything after a ‘//’ is comment and is ignored by the program class WhileLoop { static void main( String[] args ) { int loop_count = 1; while (loop_count