Hello,
is there any chance to do it in a fashion way?
I want get this:Code:for (int i=5; i >= 0; i--) {
System.out.prinln( space*i + "Hello world!");
}
thanksCode:Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Printable View
Hello,
is there any chance to do it in a fashion way?
I want get this:Code:for (int i=5; i >= 0; i--) {
System.out.prinln( space*i + "Hello world!");
}
thanksCode:Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
A techique to generate a String of blanks:
Have a String of enough blanks/spaces for the largest request
Use the substing method with an expression based on i to extract as many spaces as are needed for this usage.
Something like this:
Code:" ".substring(0, i);
OK, isn't there a way to don't use substring method ? I mean to use just the 'i' ?
i is an int. What you want is a String of blanks. I don't know how to convert an int to a String of blanks.
Perhaps you are thinking of the printf() method. It has a way of formatting data that could include leading blanks.
regex is for pattern matching. I don't know if you can generate strings based on the value of an int using it.
Write your own method to return the number of spaces you want:
String spaces(int numberOfSpaces) { ...
The String.format method can do padding:To me programming is more than an important practical art. It is also a gigantic undertaking in the foundations of knowledge...Code:int length = 20; // 20 spaces
String foo = String.format("Start of padding:'%1$"+length+"s' end of padding", "");
System.out.println(foo);
Grace Hopper
Another option if you don't mind using a third-party library:
org.apache.commons.lang.StringUtils.repeat
You can get the library here:
http://commons.apache.org/
Yet another option is this code I posted several years ago.
Here is the code snippet....
=============================
for(int i=5;i>=0;i--){
String blankString = new String();
for(int temp = i;temp>0;temp--){
blankString = blankString+" ";
}
System.out.println(blankString+"hello world");
}
}
=============================
for(int temp = i;temp>0;temp--){
blankString = blankString+" ";
Waste of CPU time.
OK thanks but I need something different:
Is there a compact way to create a white space string in a shot inside "createWhiteSpace(int num)" ? I thight to use stringFormat even I don't know how; other ideas? (compact, please)Code:String createWhiteSpace(int num) {
String spaces = .........................
return spaces;
}
//main
//let args from command line to be '10'
System.out.println("|" + creatingWhiteSpace(args[0]) + "|" );
thanks
Why compact? What is the requirement for compact?
args from command line to be "10" <<<<- note args is a String array, not an int