Java Reference
In-Depth Information
26.
Consider the following Java method, which is written incorrectly:
// This method should return how many of its three
// arguments are odd numbers.
public static void printNumOdd(int n1, int n2, int n3) {
int count = 0;
if (n1 % 2 != 0) {
count++;
} else if (n2 % 2 != 0) {
count++;
} else if (n3 % 2 != 0) {
count++;
}
System.out.println(count + " of the 3 numbers are odd.");
}
Under what cases will the method print the correct answer, and when will it print an incorrect answer? What should
be changed to fix the code? Can you think of a way to write the code correctly without any
if/else
statements?
Exercises
1.
Write a method called
fractionSum
that accepts an integer parameter
n
and returns as a
double
the sum of the
first
n
terms of the sequence
n
1
i
a
i
=
1
In other words, the method should generate the following sequence:
1
2
+
1
3
+
1
4
+
1
5
+
Á
1
+
You may assume that the parameter
n
is nonnegative
.
2.
Write a method called
repl
that accepts a
String
and a number of repetitions as parameters and returns the
String
concatenated that many times. For example, the call
repl("hello", 3)
should return
"hellohellohello"
. If the number of repetitions is zero or less, the method should return an empty string.
3.
Write a method called
season
that takes as parameters two integers representing a month and day and returns a
String
indicating the season for that month and day. Assume that the month is specified as an integer between 1
and 12 (1 for January, 2 for February, and so on) and that the day of the month is a number between 1 and 31. If the
date falls between 12/16 and 3/15, the method should return
"winter"
. If the date falls between 3/16 and 6/15, the
method should return
"spring"
. If the date falls between 6/16 and 9/15, the method should return
"summer"
. And
if the date falls between 9/16 and 12/15, the method should return
"fall"
.
4.
Write a method called
pow
that accepts a base and an exponent as parameters and returns the base raised to the given
power. For example, the call
pow(3, 4)
should return
3 * 3 * 3 * 3
, or
81
. Assume that the base and exponent
are nonnegative.
Search WWH ::
Custom Search