printf Table
Author |
Message |
Prince Pwn
|
Posted: Tue Jan 12, 2010 5:48 pm Post subject: printf Table |
|
|
Java: |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mypkg;
/**
*
* @author Prince Pwn
* @date 1/12/2010
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("number\tsquare\tcube");
for (int i = 0; i <= 10; i ++)
System.out.println(i + "\t" + i * i + "\t" + i * i * i);
//for (int i = 0; i <= 10; i++)
//System.out.printf("%d \n", i);
}
}
|
This prints a table but it's not nicely formatted. I tried using printf but I'm not sure how I can do the squared and cubed with printf. Any ideas? |
|
|
|
|
![](images/spacer.gif) |
Sponsor Sponsor
![Sponsor Sponsor](templates/subSilver/images/ranks/stars_rank5.gif)
|
|
![](images/spacer.gif) |
DemonWasp
|
Posted: Tue Jan 12, 2010 7:09 pm Post subject: RE:printf Table |
|
|
First, remember that System.out is just a member of the System class. That should lead you to the reference page for the System class. Note that the declared type of out is PrintStream? Clicking on that leads you to the documentation page for PrintStream!
It has two printf methods, one of which supports a Locale; since you don't have one, click on the other, which takes you to the method description for PrintStream.printf. Read its comment. Behold, it says how to output things!
You want System.out.printf ( "%d\t%d\t%d\n", (i), (i * i), (i * i * i) ); . Notice how the number of %d entries matches the number of integers I intend to output. |
|
|
|
|
![](images/spacer.gif) |
|
|