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 numbers 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:
A call of hopscotch(0); should print only the number 1. If it is passed a negative value, the method should produce no output.
package indefinite_loops;
public class HopScotch {
// implementation method
public void hopScotch(int value) {
// returns if the number is negative value
if (value < 0)
return;
int presentNumber = 1;
int totalNumbers = 3 * value + 1;
// run the loop till present number equals total number
while (presentNumber < totalNumbers) {
if ((presentNumber - 1) % 3 == 0) {
System.out.println(" " + presentNumber);
// increment the current value
presentNumber++;
} else {
System.out.println(presentNumber + " " + (presentNumber + 1));
presentNumber = presentNumber + 2;
}
}
System.out.println(" " + presentNumber);
}
public static void main(String[] args) {
// call the method
new HopScotch().hopScotch(4);
}
}
Output:
1
2 3
4
5 6
7
8 9
10
11 12
13