Re: System.out.print -align
This is quite simple really, you just need to check to see the value of the number and insert chars or spaces before you print the number, ie, if you have the following numbers: 4 16 100, why not make then 004, 016 and 100? Here is a quick and dirty example of this in action with comments:
Code Java:
// Okay, this is an example to line up numbers so that the last
// or least significant number is aligned, let's see how we can
// do this in Java, eh? First, we need to declare our class name
// or something.
public class Align
//Right, let's get into the main routine
{
public static void main (String args [])
{
// Okay, let's set up some variables:
int eye=0;
int number=0;
// Here is our loop:
for (eye=1;eye<=10;eye=eye+1)
{
// Okay, we'll make the variable number a random
// number less that 100? Or will it be less than
// 101? I can't remember, but in some languages,
// if you want an integer number to 100 then you
// have to specify 101, so to be on the safe
// side, and assuming that we want a number up to
// 100, we'll ask for a number up to 101:
number=(int)(Math.random()*101);
// Right, let's start off with a space using print,
// print will not put a line feed after it, which
// we'll do when we've actually printed the number
// out with 'println':
System.out.print(" ");
// Here are our conditions so...
if (number<10)
{
// we'll put two digits in front of the number
System.out.print("00");
// or...
}
else if (number>=10 && number<100)
{
// we'll put one digit in front of the number
System.out.print("0");
}
// now, we'll print the number with a line feed after it
System.out.println(number);
// Just a note: I'm going to assume that you may replace
// the nuaghts with spaces to align the numbers to the
// right :-) Enjoy! Shaun Bebbington MMX
}
}
}
Simple, eh?
Regards,
Shaun.
Re: System.out.print -align
Read the API for String#format(...) and PrintStream#printf(...). And you'll want to to get the details of formats from Formatter.
db
Re: System.out.print -align
Alternatively, you can use printf, which is used in C.
When using printf, you use placeholders which you can format. The placeholder for int is %d. If you want to indicate that all numbers should have 2 spaces, you use the placeholder %2d. If you want all numbers to hold 2 spaces and have a leading zero if the space(s) in front of the number would otherwise be just an empty space, you use the placeholder %02d.
So, if you want all of your numbers to be aligned without leading zeros, your code would look like this:
Code java:
int number = 0;
for(int i=1; i<11; i++){
number = (int) (Math.random()* 100);
System.out.printf("%2d", number);
}
If you want all of your numbers to be aligned with leading zeros, your code would look like this:
Code java:
int number = 0;
for(int i=1; i<11; i++){
number = (int) (Math.random()* 100);
System.out.printf("%02d", number);
}