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”.
(Solve this without if statement)
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;
}
Expert Answer
JavaCode:
StringPading.java:
import java.util.Scanner;
public class StringPading{
public static void main(String []args){
String str;//variables
int noOfSpaces;
Scanner sc=new Scanner(System.in); //Scanner object
System.out.print(“Enter the String :”); //Getting the String entered by the user
str=sc.next();
System.out.print(“Enter no of Spaces :”);//Getting the number of spaces
noOfSpaces=sc.nextInt();
String newString=padString(str,noOfSpaces);
System.out.println(“New String :”+newString); //Displaying the string
}
private static String padString(String str, int noOfSpaces) // append spaces to the beginning of the string
{
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: