Object Instantiation with Static Validation
Consider the following TempTest and Temperature class definitions. Which code segment is the best replacement for /* code to construct a valid temperature from user input */ in the main method of the TempTest class?
public class TempTest {
public static void main(String[] args) {
System.out.println("Enter temperature scale: ");
String tempScale = ...; // read user input
System.out.println("Enter number of degrees: ");
double tempDegrees = ...; // read user input
/* code to construct a valid temperature from user input */
}
}
public class Temperature {
private String scale; // valid values are "F" or "C"
private double degrees;
/** constructor with specified degrees and scale */
public Temperature(double tempDegrees, String tempScale) {
/* implementation not shown */
}
/** Returns true if tempDegrees is a valid temperature
* in the given temperature scale, false otherwise.
*/
public static boolean isValidTemp(double tempDegrees, String tempScale) {
/* implementation not shown */
}
// Other methods are not shown.
}
A
if (isValidTemp(tempDegrees, tempScale)) {
Temperature t = new Temperature(tempDegrees, tempScale);
} else {
// error message and exit program
}
B
Temperature t = new Temperature(tempDegrees, tempScale);
C
Temperature t = new Temperature(tempDegrees, tempScale);
if (Temperature.isNotValidTemp(tempDegrees, tempScale)) {
// error message and exit program
}
D
if (Temperature.isValidTemp(tempDegrees, tempScale)) {
Temperature t = new Temperature(tempDegrees, tempScale);
} else {
// error message and exit program
}
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 2 | 2 | 0m 00s | 200 |
| #2 | bommasam000 | 3 | 6 | 6m 19s | -109 |
| #3 | y.seong2027 | 1 | 2 | 170h 18m | -613,020 |
Items per page:
10
1 – 3 of 3
APFIVE