Java print a number table with alignment

Question

We would like to write a program that displays the following table

a      a^2    a^3 
1      1      1 
2      4      8 
3      9      27 
4      16     64 

Code structure

public class Main {
  public static void main(String[] args) {
    //your code here
  }
}



public class Main {
  public static void main(String[] args) {
    System.out.println("a  a^2   a^3");
    System.out.println("1  1     1");
    System.out.println("2  4     8");
    System.out.println("3  9     27");
    System.out.println("4  10    64");
  }
}

Note

You can also use the for loop and printf method.


public class Main {
  public static void main(String[] args) {
    System.out.println("a       a^2     a^3");
    for (int i = 1; i <= 4; i++) {
      System.out.printf("%-3d     %-3d     %-3d\n", i, i * i, i * i * i);
    }/* w w w . ja va2 s .  c  o m*/
  }
}



PreviousNext

Related