Write a method padString that accepts two parameters: a String and an integer re
ID: 3817206 • Letter: W
Question
Write a method 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) would return "congratulations".
Explanation / Answer
PaddingString.java
import java.util.Scanner;
public class PaddingString {
public static void main(String[] args) {
//Declaring variables
String str;
int noOfSpaces;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//Getting the String entered by the user
System.out.print("Enter the String :");
str=sc.next();
//Getting the number of spaces
System.out.print("Enter no of Spaces :");
noOfSpaces=sc.nextInt();
/* calling the method by passing the string
* and no of spaces as arguments
*/
String newString=padString(str,noOfSpaces);
//Displaying the string
System.out.println("New String :"+newString);
}
//This method will append spaces to the beginning of the string
private static String padString(String str, int noOfSpaces) {
String newStr="";
int addSpaces;
if(str.length()==noOfSpaces)
return str;
else
{
addSpaces=noOfSpaces-str.length();
for(int i=1;i<=addSpaces;i++)
newStr+=" ";
newStr+=str;
}
return newStr;
}
}
___________________
Output#1:
Enter the String :hello
Enter no of Spaces :8
New String : hello
___________________
Output#2:
Enter the String :Congratulations
Enter no of Spaces :10
New String :Congratulations
____________Thank You
Please rate me well.If you area satisfied.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.