Formatting white space to 3 characters in parentheses
Hello,
In my program i have to count a certain number of days and increase the counter as it goes through the loop. I have to display this number in parenthesis with exactly 3 spaces(including numbers) enclosed in the parenthesis as see below:
Yearly temperature data for Denver
<= 9 ( 3):***
10 - 19 ( 4):****
20 - 29 ( 9):*********
30 - 39 ( 27):***************************
40 - 49 ( 47):********************************************** *
50 - 59 ( 66):********************************************** ********************
60 - 69 ( 62):********************************************** ****************
70 - 79 ( 44):********************************************
80 - 89 ( 66):********************************************** ********************
90 - 99 ( 37):*************************************
>=100 ( 0):
How would i make it to where the parentheses only allow 3 characters at all times? Meaning that if it was 5 it would just show ( 5) <----- has two spaces before the 5, and if it was 15 it would just show ( 15)<----has one space before the 15, and if it was 114 it would show (114) <----no spaces, just numbers
i am using the format method right now and if i use "000" it will still show the leading zero(for two digit numbers)...if i use "###" it will just display the number by itself and no spaces at all.
any help would be greatly appreciated! Thank you!!
Re: Formatting white space to 3 characters in parentheses
Consider using the String.format() method. The format string is described in detail in the Formatter API linked to from there. They take a little getting used to, but are quite flexible.
Code :
public class FormatterEg {
public static void main(String[] args) {
int[] data = {-5, 0, 1, 42, 666};
for(int test :data) {
System.out.printf("(%3d)%n", test);
}
// once more, with precision...
double[] data2 = {-1, 0, Math.PI, Math.E};
for(double test :data2) {
System.out.printf("(%-8.4f)%n", test);
}
}
}
The first format string means:
( literal left parenthesis
% format
3 three wide
d decimal integer
) literal right parenthesis
%n new line
The second one illustrates how a fixed number of decimal places can be obtained (with correct rounding).
( literal left parenthesis
% format
- left align
8 eight wide
.4 including four decimal places
f floating point number
) literal right parenthesis
%n new line