W2 Homework Solutions

P52 problems

Problem 1:

Prompt user for length of side of the square.

Convert input length (String) to numeric.

Compute square's area (length*length)

Display/output resulting area to user.

Problem 3:

The answer is subject to discussion, and the textbook author does not really make this clear. But in "real" java, any code after an iteration (like a while) or after a condition (like an if) should be surrounded by braces to clearly indicate what should be executed. Indentation is not enough to indicate what code is "really" within the body of the iteration/condition.
 

Problem 4:

The answer to this problem depends on what code you consider to be within the body of the while condition. If you suppose that both of the statements following the while are executed, then the value for time starts at 3. While time is less than 8 (that is: 3,4,5,6,7), the statements repeat, producing 5 lines of output. However, if only the first line of code is repeated (print time), then the time variable is never incremented, and the loop repeats forever (infinite loop), printing the value of 3 forever.

 

P102 problems

Problem 1:

/* Here is a comment. Everything between the slash-star and star-slash is ignored */

/*
Here is another comment; the slash-star and star-slash don't have to be on the same lines.
*/

// Here is the other comment form; no ending slashes are needed

Problem 2:

Main must begin with lowercase "m"

Problem 3:

Braces clearly indicate what statements are within a body of code of a conditional or repetition statement.

Problem 5:

False. The correct answer is "use camel-case notation, capitalizing each word after the first, which begins with a lowercase letter".

Problem 6:

_isReady: legal, but unconventional to begin with an underscore
3rdName: illegal; cannot begin with a digit
num of wheels: illegal; cannot contain spaces
money#on#hand: illegal; cannot contain #; only _ and $ are permitted with an identifier
taxRate: legal and conventional (camel-case, noun-phrase)
SeatNumber: legal, but unconventional for a variable; only class names should begin with uppercase.