## CPSC 124, Spring 2006

Answers to Quiz #2

Question 1:Suppose thatstris a variable of typeString. What is the meaning of the expressionstr.charAt( str.length() - 1 )?

Answer:This value of this expression is the final character in the stringstr. For example ifstris "cat", then the value is 't'. This is becausestr.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 atstr.length() - 1, wherestr.length()is the number of characters in the string. (Note: This expression produces anerrorin the case wherestris the empty string.)

Question 2:Suppose thatctis a variable of typeint. What is the effect of the statementct++;?

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

Question 3:What is the difference between the statementsx = TextIO.getlnDouble();andx = 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 of4*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.995areincluded 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()),Nis the number of possible values andMis 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".

Answer: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