I need to recieve a integer and have it print out that number of spaces in between the letters of a name. Right now I have it printing out one space.
public static void printLongName(int spaces){
String name
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.print(" " + letter[i]);
System.out.println();
}
use System.out.format()
System.out.format("%10c", letter[i]);
update
int spaces=10;
String name ="aaaaaaaa";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++)
System.out.format("%10c", letter[i]);
public static void printLongName(String name, int numOfSpacesBetweenLetters) {
StringBuffer sbSpace = new StringBuffer();
for (int i = 0; i <= numOfSpacesBetweenLetters; i++) {
sbSpace.append(" ");
}
char[] letter = name.toCharArray();
for (int i = 0; i < letter.length; i++) {
System.out.println(sbSpace + letter[i]);
}
}
//System.out.print(" " + letter[i]);
//System.out.print(getSpace(10) + letter[i]);like this you can
public String getSpace(int count)
{
String space="";
for(int i=0;i<count;i++)
space+=" ";
return space;
}
I believe your looking for something like this:
System.out.format("[%13s]%n", ""); // prints "[ ]" (13 spaces)
System.out.format("[%1$3s]%n", ""); // prints "[ ]" (3 spaces)
This regular expression will allow you to add your spaces appropriately.
You need build the space string first with parameter input. Please look at below code:
public static void printLongName(int spaces){
String name = "hello";
StringBuilder sb = new StringBuilder();
String spaceStr = "%"+spaces+"c";
char[] letter = name.toCharArray();
for(int i = 0; i < letter.length; i++) {
if (i == 0) {
sb.append(letter[i]);
} else {
sb.append(String.format(spaceStr, letter[i]));
}
}
System.out.println(sb);
}
public static void main(String[] args) {
printLongName(4);
}
Update some code.
This function will return a string with spaces:
String nameWithSpaces(String name, int spaces) {
StringBuilder sbname = new StringBuilder(name);
String spaces = String.valueOf(new char[spaces]).replace("\0", " ");
for (int i=1; i < sbname.length(); i += spaces.length()+1)
sbname.insert(i, spaces);
return sbname.toString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.