Java Reference
In-Depth Information
9. Write a method called printFactors that accepts an integer as its parameter and uses a fencepost loop to print the
factors of that number, separated by the word "and" . For example, the factors of the number 24 should print as the
following:
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
You may assume that the parameter's value is greater than 0 , or you may throw an exception if it is 0 or negative.
Your method should print nothing if the empty string ( "" ) is passed.
10. Write a method called hopscotch that accepts an integer number of “hops” as its parameter and prints a pattern of
numbers that resembles a hopscotch board. A “hop” is a three-number sequence where the output shows two num-
bers on a line, followed by one number on its own line. 0 hops is a board up to 1; one hop is a board up to 4; two
hops is a board up to 7; and so on. For example, the call of hopscotch(3); should print the following output:
1
2 3
4
5 6
7
8 9
10
A call of hopscotch(0); should print only the number 1. If it is passed a negative value, the method should pro-
duce no output.
11. Write a method called threeHeads that repeatedly flips a coin until the results of the coin toss are three heads in a
row. You should use a Random object to make it equally likely that a head or a tail will appear. Each time the coin is
flipped, display H for heads or T for tails. When three heads in a row are flipped, the method should print a congrat-
ulatory message. Here is a possible output of a call to the method:
T T H T T T H T H T H H H
Three heads in a row!
12. Write a method called printAverage that uses a sentinel loop to repeatedly prompt the user for numbers. Once the
user types any number less than zero, the method should display the average of all nonnegative numbers typed.
Display the average as a double . Here is a sample dialogue with the user:
Type a number: 7
Type a number: 4
Type a number: 16
Type a number: -4
Average was 9.0
If the first number that the user types is negative, do not print an average:
Type a number: -2
13. Write a method called consecutive that accepts three integers as parameters and returns true if they are three
consecutive numbers—that is, if the numbers can be arranged into an order such that, assuming some integer
,
k
the parameters' values are
k + 2 . Your method should return false if the integers are not consecu-
tive. Note that order is not significant; your method should return the same result for the same three integers passed
in any order.
,
k + 1 , and
k
Search WWH ::




Custom Search