SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:10 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.