School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 4: Storing and Manipulating Data
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 2 Storing and Manipulating Data Declarations Variables
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 3 Declarations A recipe ingredient list helps –prepare in advance –ensure have enough of everything Declarations are similar in programming –instructions to compiler "these are the resources I need" resources are the places where values can be stored (variables and constants)
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 4 Variables named ‘pigeon holes’ in memory, in which we can store data items. Each variable has a type, which restricts the sort of data that can be stored in the variable. To use variables in our program, we must first declare them like this: int age; Declares a variable called age, of type int. This is a box into which we are allowed to place integers (whole numbers – i.e. no decimal point).
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 5 Integer Declarations int a; This statement declares a variable a to hold integer values –ie whole numbers.. -2, -1, 0, 1,2,... a is a "box" to keep integers in It creates the box but it is undefined to start with... it's empty This statement gives information to the compiler –rather than a step in the plan
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 6 Variables char letter; This declares a variable called letter, of type char. This is a box into which we are allowed to place characters. double distance; This declares a variable called distance, of type double, into which we may place double precision floating point numbers (up to 15 significant digits).
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 7 Variables Note that variable declarations always end with a semicolon. A variable declaration tells the compiler to allocate space in the computer’s memory for the variable. Always give variables meaningful names, from which a reader might be able to make a reasonable guess at their purpose. Use comments if further clarification is necessary int temperature; // in celsius legal identifiers - rules - keywords
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 8 Identifiers An identifier is just the name of a thing we have declared int a; this declares a new integer variable its identifier (ie name) is a Which is what you use to refer to it Other things have identifiers –eg methods public static void main() {...} –this declares a method with identifier main
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 9 What makes an identifier must start with –a letter a, b, A,... can then consist of –letters –digits –underscores but must not be a keyword Upper and lower case characters are treated as different letters
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 10 Keywords Some names are reserved by Java –they cannot be used as identifiers –they are already used for other things –the compiler would get confused if they were also used as identifiers –the special names are called keywords –we have used some already
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 11 Identifier Style Names should be meaningful –temperature not t Comment the declaration –if further clarification is needed –describe the variable's use e.g. int temperature; // in celsius
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 12 The Assignment Statement How do we place data items into variables? Read in values typed at the keyboard by the user (see later) Use an assignment statement Assignment statement examples: age = 21; letter = ‘A’; // Note a character value is indicated by single quotes distance = 6.4;
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 13 The Assignment Statement On the left of the = is always the name of a variable. On the right of the = is an expression of the same type as the variable on the left. The order of events when the computer executes an assignment statement is - Evaluate the expression on the right hand side of the = - Store the resultant value of the expression in the variable on the left hand side of the =
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 14 What happens? int age, timePassed;. timePassed = 5; age = ; age = 16 + timePassed; age = age + 6; age = age + timePassed;
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 15 Assignment Each time a new value is stored in a variable, the old one is overwritten. = does not mean ‘equals’. It is a command to the computer telling it to store the value of the expression on the right in the variable on the left. You could read the = sign as ‘becomes equal to’. When a variable’s value is used on the right hand side of an assignment statement, this does not change its value.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 16 Question What is the difference between the statements letter = ‘a’; letter = a; Answer In the first statement, the character value ‘a’ is being stored in variable letter In the second statement, the contents of a variable called a will be copied into variable letter
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 17 Output of non-string data System.out.println( "I only output strings!"); System.out.println( "I only output strings! " + “Really I do!”); System.out.println( "The answer is " + 42); int answer = 42; System.out.println( "The answer is " + answer );
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 18 Question What would this code fragment print? char ch = ‘t’; System.out.println( "I love the " + ch + "aste of Java");
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 19 Doing calculations Addition + Subtraction – Multiplication * Division / Modulus %. / does ordinary division when applied to floating point numbers (doubles), but integer division when applied to integers.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 20 Question What does this program fragment do? int a = 2; int b = 3; System.out.println( "a + b"); System.out.println( "The question is " + a + "+" + b); System.out.println( "The answer is " + (a + b) );
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 21 Question System.out.println( "The answer is " + a + b );
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 22 Priority and Precedence in expressions 1.Evaluate things in parentheses (). If they are nested start at the innermost. Evaluate non-nested parenthesis left to right. 2.Evaluate * / % If there are several, evaluate left to right. 3.Evaluate + - If there are several, evaluate left to right
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 23 A VAT program We will now look at how we can write a program to do a calculation and print the result on the screen. Suppose we wish to know the Value Added Tax (VAT) to be paid on a purchase price of £67. The current rate of VAT is 17.5%. The calculation required is therefore (17.5 * 67) / 100
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 24 // Computes the VAT to be paid on a purchase price of £67 // Assumes VAT rate of 17.5% import javax.swing.JOptionPane; // import class JOptionPane public class calcVAT { public static void main( String args[] ) { final double VATRATE = 17.5; // percentage VAT rate double price = 67; // purchase price double vat; // VAT to be paid // do the calculation vat = price * VATRATE / 100; // output the answer JOptionPane.showMessageDialog(null, "VAT to pay is " + vat ); System.exit( 0 ); // terminate the program }
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 25 A VAT program Note that in the statement vat = price * VATRATE / 100; the / operator will do floating point division because its first operand is a floating point number. In general, it would be safer to make both operands into floating point numbers, to make it clear to the reader what is intended. vat = price * VATRATE / 100.0;
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 26 Constants In the declaration final double VATRATE = 17.5; the keyword final prevents the variable VATRATE from being changed during the running of the program. VATRATE is a named constant; whenever we use the name VATRATE, it stands for the number Conventionally written in capitals.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 27 Advantages Why not just use the number 17.5 in our calculation? The name VATRATE is more meaningful, as one might not know what the current rate of VAT happens to be. Changing large programs Note that this program is limited, as it only computes the VAT to pay on one price, namely £67. The program would be much more useful if the user could type in any price at the keyboard, and have the program compute the VAT on that price.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 28 Syntax errors Spelling, punctuation or grammar of the program. Spelling English “The mewn ys maid of blew cheeze” Java “ publec statec vood mayn(Streng args[])” Punctuation English “John said why study Java he then tore up Deitel and Deitel” Java “System exit 0)” Grammar English “Would to like dance me you with?” Java “ 42 = ; answer”
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 29 Syntax errors You do not need to know the meaning of the sentences to see these are mistakes, just the rules for constructing them. Common Java syntax errors include missing semicolons from the end of lines. using capital letters inappropriately: for example using INT or Int instead of int
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 30 Syntax errors Syntax errors are detected by the compiler. Sometimes the compiler messages can be misleading If you can’t see an error on the line it tells you to look on, take a look at the previous few lines. Sometimes the compiler will tell you that there are lots of errors; try fixing the first few, then recompile – often errors later in the program are generated because of earlier ones!
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 31 Semantic errors A semantic error is an error in the meaning of the statements in the program. The program is a valid Java program which can be executed, but it doesn’t do what it is supposed to. Such errors are also called logic errors. For example English “Windsurf up the stairs” Java “age = -20 // negative age!” A flight simulator program that allows you to fly through mountains The Y2K Bug.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 32 Semantic errors Some logic errors are detected only by running (or dry-running) the program with appropriate test data Others, sometimes called run-time errors, manifest themselves when the program is running. For example: num = 42 / 0; // division by zero; Suppose spling calls splong, and splong calls spling – the program will run forever. Because the program is syntactically correct Java, the compiler cannot detect logic errors.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 33 Semantic errors Semantic errors indicate mistakes in the algorithm… … the program does something - it is just that it does the wrong thing. A large, complex program with an obscure logic error may run correctly for years before hitting the problem. Sometimes it proves impossible to cure the error. The error is simply documented, and the users try to avoid running the program with the data that caused the error to occur. Missile defence system? Nuclear power station? Fly-by-wire aircraft? Life support machine?