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:
Conditional Execution
Exercise:
Exercises
Question:2 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch04Ex02
{
	public static void main(String[] args)
	{
		System.out.println("repl(\"hello\", 0): " + repl("hello", 0));
		System.out.println("repl(\"hello\", 1): " + repl("hello", 1));
		System.out.println("repl(\"hello\", 3): " + repl("hello", 3));
	}

	public static String repl(String str, int times)
	{
		String result = "";

		for (int i = 0; i < times; i++)
		{
			result += str;
		}

		return result;
	}
}

Output:

repl("hello", 0): 
repl("hello", 1): hello
repl("hello", 3): hellohellohello

 

0 0

Discussions

Post the discussion to improve the above solution.