Assignment W1--Solutions
CS 100 � Summer 1999
Due Date: July 1, 1999
TA: Alan Renaud
The compile-time error in (8) is the undeclared per2 variable; but line (8) is also guilty of a logic error: remainder division uses the % symbol�not the / symbol.
Line (3) is technically a syntax error, as the code should be public static void main (String args[]) not �. (String [] args)
The valid but still not good identifiers are index (too vague) and
the_next_name_in_the_list_that_starts_with_b (way, way too long).
Whether PDG_name is good or not will depend upon the context.
In general, try to choose short and meaningful variable names; they help make your programs "self-documenting".
5. Here's how the different variables match up in a table:
type |
size in bits |
values |
byte |
8 |
-128 to 127 |
short |
16 |
-32,768 to 32767 |
int |
32 |
-2147483648 to + 2147483647 |
float |
32 |
-3.40292347E+38 to +3.492923447E+38 |
double |
64 |
-1.79769313486231570E+308 to +1.7969313486231570E + 308 |
Good programmers try to choose appropriate variable types for each problem. Hence, it would not be sensible to write a factorial method with variables that are all int, as your program would very quickly need numbers bigger than int can provide. Conversely, you would be ill-advised to use a variable of type double to count the number of students in a classroom, too much byte space for too little data.
if (total == MAX)
if (total < sum)
System.out.println ("total equals MAX and total is"
+ " less than sum");
else
System.out.println("total is not equal to MAX");
The body of the first if structure is another if/else structure.
The first structure tests to see if total is equal to MAX. If true, the execution proceeds by testing if total is also less than sum; if that is also true, the proper string�"total equals MAX and total is less than sum"�is displayed. However, if the second condition is false the string "total is not equal to MAX" is displayed even though we know total is equal to MAX.
To force the code fragment to execute as it was originally intended, rewrite the structure as follows:
if (total == MAX) {
if (total < sum)
System.out.println ("total equals MAX and total is"
+ " less than sum");
}
else
System.out.println("total is not equal to MAX");