CPSC 124, Spring 2006
Answers to Quiz #2

Question 1: Suppose that str is a variable of type String. What is the meaning of the expression str.charAt( str.length() - 1 ) ?

Answer: This value of this expression is the final character in the string str. For example if str is "cat", then the value is 't'. This is because str.charAt(n) represents the n-th character in the string, where the characters are numbered starting at 0. In this numbering, the final character is at str.length() - 1, where str.length() is the number of characters in the string. (Note: This expression produces an error in the case where str is the empty string.)

Question 2: Suppose that ct is a variable of type int. What is the effect of the statement  ct++;  ?

Answer: The effect is to change the value stored in ct by adding one to that value. If the value of ct is 3 before the statement is executed, then after the statement is executed its value will be 4. This is very different from the expression ct + 1 which simply computes a value without changing the value of ct.

Question 3: What is the difference between the statements   x = TextIO.getlnDouble();   and   x = TextIO.getDouble();  ?

Answer: Both statements read one real number from input typed by the user. The first version (with "getln") then discards any extra characters on the line of input. In the second version, the extra characters are still there (in a "buffer") and can be read by subsequent input statements.

Question 4: What are the possible values of the expression   (int)(2 + 4*Math.random())  ?

Answer: The value of 4*Math.random() is a real number in the range from 0.0 to 4.0, but not including 4.0 exactly. (Numbers such as 3.9 and 3.995 are included as possibilities.) Adding 2 gives a number in the range 2.0 to 6.0, not including 6. The type case operator (int) throws away the fractional part of the number, leaving an integer value that can be either 2, 3, 4, or 5. (Note: In the expression (int)(M + N*Math.random()), N is the number of possible values and M is the first possible value.)

Part 2: There are 5280 feet in a mile. Write a program that converts a measurement given in feet to a measurement given in miles. The program should ask the user to enter the number of feet, and it should output the converted measurement. For example, if the user enters 16650, the program should output "That is 3 miles and 810 feet".


        public class Feet {
            public static void main(String[] args) {
                int feet, miles, extraFeet;
                System.out.print("What is the number of feet?  ");
                feet = TextIO.getlnInt();
                miles = feet / 5280;
                extraFeet = feet % 5280;
                System.out.println("That is " + miles + " and " + extraFeet + " feet.");

David Eck, 3 February 2006