Java Reference
In-Depth Information
21. Write code to examine a String and determine how many of its letters come from the second half of the alphabet
(that is, have values of 'n' or subsequent letters). Compare case-insensitively, such that values of 'N' through 'Z' also
count. Assume that every character in the String is a letter.
Section 4.4: Methods with Conditional Execution
22. Consider a method printTriangleType that accepts three integer arguments representing the lengths of the sides
of a triangle and prints the type of triangle that these sides form. The three types are equilateral, isosceles, and sca-
lene. An equilateral triangle has three sides of the same length, an isosceles triangle has two sides that are the same
length, and a scalene triangle has three sides of different lengths.
However, certain integer values (or combinations of values) would be illegal and could not represent the sides of
an actual triangle. What are these values? How would you describe the precondition(s) of the printTriangleType
method?
23. Consider a method getGrade that accepts an integer representing a student's grade percentage in a course and
returns that student's numerical course grade. The grade can be between 0.0 (failing) and 4.0 (perfect). What are
the preconditions of such a method?
24. The following method attempts to return the median (middle) of three integer values, but it contains logic errors. In
what cases does the method return an incorrect result? How can the code be fixed?
public static int medianOf3(int n1, int n2, int n3) {
if (n1 < n2) {
if (n2 < n3) {
return n2;
} else {
return n3;
}
} else {
if (n1 < n3) {
return n1;
} else {
return n3;
}
}
}
25. One of the exercises in Chapter 3 asked you to write a method that would find the roots of a quadratic equation of
the form ax 2 + bx + c = 0. The quadratic method was passed a , b ,and c and then applied the following quadratic
formula:
b 2
-
b
; 2
-
4 ac
x
=
2 a
Under what conditions would this formula fail? Modify the quadratic method so that it will reject invalid values
of a , b , or c by throwing an exception. (If you did not complete the exercise in the previous chapter, just write the
method's header and the exception-throwing code.)
Search WWH ::




Custom Search