## CPSC 124, Fall 2005

Answers to Quiz #2

Question 1:Suppose thatstris a variable of typeStringthat has value"Fred". What is the value ofstr.charAt(1)? Why?

Answer:The value ofstr.charAt(1)is the character'r'.str.charAt(n)is the character at position numbernin the stringstr. Since positions are numbered 0, 1, 2, ..., the character at position 1 in"Fred"is'r'.

Question 2:Suppose that the statementok = !( x < 0 || x > 100 );occurs in a Java program. Assume thatxis a variable of typedoublethat has value 98.6. What type of variable doesokhave to be, and and what value does this statement assign took?

Answer:The expression"!( x < 0 || x > 100 )"is atestthat computes a boolean value (eithertrueorfalse). (The expression means "it is not the case that x is less than 0 or x is greater than 100".) Since the boolean value of this test is assigned took,okmust have typeboolean. In this case, x is 98.6. So"x < 0"is false and"x > 100"is also false. This means that"x < 0orx > 100"is false. Since the"!"operator reverses a boolean value,"!( x < 0 || x > 100 )"is true. So, the value assigned tookistrue.

Question 3:Give three different examples ofliterals, representing three differenttypesof values. State the type of each literal, using a valid Java type name.

Answer:We have seen five major types of literals: int, double, String, boolean, and char. Here is an example of a literal of each of these types:int: 42 double: 17.3 String: "Hello World!" boolean: false char: 'A'

Question 4:What is aninfinite loop, and how could such a thing happen?

Answer:An infinite loop is a loop that continues running indefinitely. This can happen when the exit condition, which is tested to determine whether or not to end the loop, never becomes true. When a program is in an infinite loop, it must be terminated externally in some way (such as pressingCONTROL-Con the command line in Linux).

Part 2:Write a code segment that asks the user to enter an integer, then reads the integer from the user, then writes out all the integers from 1 up to the number entered. The output numbers should be on one line, separated by spaces. For example, if the user types in the number 7, then the output would be:1 2 3 4 5 6 7

Answer:Here is one possible answer:int userNum; // The number read from the user. int outputNum; // A number to be printed. System.out.print("Please enter an integer: "); userNum = TextIO.getlnInt(); outputNum = 1; // The first number to be printed. while (outputNum <= userNum) { System.out.print(outputNum); // Output the number. System.out.print(" "); // Output a space. outputNum++; // Go on to the next number }