Introduction to Programming (2001/2002): Practical 3
Goals
After completing this weeks practical, you should be able to declare, initialise and use variables, and to convert, where appropriate, from one kind to the other. Here is a little refresher of the material we did in lectures:
Remember you may store an integer value in a double variable, thus:
int anInteger = 3; // anInteger is 3 double aDouble = anInteger; // aDouble is now 3.0
but problems arise if you try to store a double in an integer variable:
double aDouble = 3.0; int anInteger = aDouble; // NOT ALLOWED!!!
We can force the matter by casting the right hand side to an integer:
double aDouble = 3.0; int anInteger = (int) aDouble;
Exercises
- Write a program which prompts for a number, and reads that in as a double. Convert that value to an integer using a type cast, and output the integer value. Test it on at least the following values: 4, 4.9, 4.1, 3.9, 0, -0, -4.1, -3.9.
- What is wrong with the following code? Fix it!
/* * Average.java: Find the average of two numbers */ public class Average { public static void main(String[] args) { int x; int y; int average; System.out.print("Enter first number: "); x = MyInput.readInt(); System.out.print("Enter second number: "); y = MyInput.readInt(); average = (x + y)/2; System.out.print("The average of the two is "); System.out.println(average); } }
- Characters in Java are encoded using the Unicode system. Under this system,
each character maps onto a number. (For those who care, the numbers are stored
in 16 bits, which allows us to encode 216
different characters). Thus there is a 1-to-1 relationship between characters
and numbers. The characters 'A', 'B', 'C'...'Z' map onto a consecutive set
of 26 Unicode values. The characters 'a', 'b', ... 'z' map onto a different
26 Unicode values, and the digits '0', '1', ...'9' map onto 10 further values.
Study the following code excerpt. What does it do?char c1 = 'A'; int i1 = (int)c1; i1 += 5; // i.e. i1 = i1 + 5 char c2 = (char) i1; System.out.println("c2 now holds " + c2);
Write a short program to try out these lines of code, and check the result. Now use your program to figure out whether the numbers which represent the uppercase letters are greater or smaller than those which represent the lowercase letters. What about the digits?
This week's problem for submission
Submit your answer to question 1. If you have not answered the question, please enter a brief description of where you got stuck. When you have entered your code, click on Send. Please submit your code only once.
IMPORTANT: Before you leave the practical session, make sure that your attendance has been noted by one of the demonstrators.