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:
Introduction To Parameters And Objects
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Write a method called padString that accepts two parameters: a string and an integer representing a length. The method should pad the parameter string with spaces until its length is the given length. For example, padString("hello", 8) should return "hello ". (This sort of method is useful when trying to print output that lines up horizontally.) If the string’s length is already at least as long as the length parameter, your method should return the original string. For example, padString("congratulations", 10) should return "congratulations".

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Ch03Ex11
{
	public static void main(String[] args)
	{
		String res1 = padString("hello", 8);
		String res2 = padString("congratulations", 10);
		
		System.out.println("\"" + res1 + "\"");
		System.out.println("\"" + res2 + "\"");
	}

	public static String padString(String str, int len)
	{
		for (int i = str.length(); i < len; i++)
		{
			str = str + " ";
		}

		return str;
	}
}

Output:

"hello   "
"congratulations"

 

0 0

Discussions

Post the discussion to improve the above solution.