Reputation: 5959
I've to write code for:
I'd written the code:
public class tables {
public static void main(String[] args) {
//int[][] table = new int[12][12];
String table="";
for(int i=1; i<13; i++){
for(int j=1; j<13; j++){
//table[i-1][j-1] = i*j;
table+=(i*j)+" ";
}
System.out.println(table.trim());
table="";
}
}
}
But the problem is with the output format. I need the output in a matrix like fashion, each number formatted to a width of 4 (the numbers are right-aligned and strip out leading/trailing spaces on each line). I'd tried google but not find any good solution to my problem. Can anybody help me out?
Upvotes: 17
Views: 71768
Reputation: 87
I made an OutputFormatter class which formats the Strings you give it:
OutputFormatter formatter = new OutputFormatter();
formatter.add("Asus", "20000");
formatter.add("INTEL", "45000");
formatter.add("Nvidia gtx 1050ti", "17000");
formatter.add("Asus", "18000");
formatter.add("Samsung", "20000");
formatter.add("Coolermaster", "20000");
formatter.add("Ortis", "4000");
formatter.add("Asus", "4000");
System.out.println(formatter.format());
The output looks like this:
Asus 20000
INTEL 45000
Nvidia gtx 1050ti 17000
Asus 18000
Samsung 20000
Coolermaster 20000
Ortis 4000
Asus 4000
You can give the add()
method on the OutputFormatter as much Strings as you would like, it takes them all into account.
This is the OutputFormatter class:
import java.util.ArrayList;
import java.util.List;
public class OutputFormatter {
private List<String[]> contents;
public OutputFormatter() {
contents = new ArrayList<>();
}
public void add(String... fields) {
contents.add(fields);
}
public void clear() {
contents.clear();
}
public String format() {
StringBuilder ret = new StringBuilder();
List<Integer> lengths = new ArrayList<>();
int maxContentLen = 0;
for (String[] row : contents) {
maxContentLen = Math.max(maxContentLen, row.length);
}
for (int i = 0; i < maxContentLen; i++) {
int len = 1;
for (String[] row : contents) {
try {
len = Math.max(len, row[i].length());
} catch (IndexOutOfBoundsException ignore) {}
}
lengths.add(len);
}
for (String[] row : contents) {
for (int i = 0; i < row.length; i++) {
ret.append(row[i] + " ".repeat(lengths.get(i) - row[i].length() + 1));
}
ret.append(System.lineSeparator());
}
return ret.toString();
}
}
Upvotes: 0
Reputation: 1331
Formatting of output can be done using the System.out.format("","") method this method contain two input parameter first define the formatting style and second define value to be print. Let us assume you want to the n digit value right align. you will pass the first parameter "%4d".
For the left align use -ve %-nd
For right align use +ve %nd
for(int i=1; i<13; i++){
for(int j=1; j<13; j++){
System.out.format("%4d", i * j); //each number formatted to a width of 4 so use %4d in the format method.
}
System.out.println(); // To move to the next line.
}
Upvotes: 0
Reputation: 117
In my example the array contains character string's with different length and due to that I was unable to arrange string and other strings of different arrays were mis-match on console. with a different concept I could arrange those arrays on console my codes are as below.
package arrayformat;
/**
*
* @author Sunil
*/
public class ArrayFormat {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int[] productId = new int[]
{1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,};
String[] productName= new String[]{"Pepsi","kissan jam","Herbal
oil","Garnier man's","Lays chips","biscuits","Bournvita","Cadbury","Parker
Vector","Nescafe",};
String[] productType = new String[]{"Cold Drink","Jam","Oil","Face
wash","chips","Biscuits","Health
Supplement","Chocolate","Stationary","Coffee",};
float[] productPrice = new float[]{24,65,30,79,10,20,140,20,150,80,};
int productNameMaxlength=0;
int productTypeMaxlength=0;
for (String productName1 : productName) {
if (productNameMaxlength < productName1.length()) {
productNameMaxlength = productName1.length();
}
}
for (String productType1 : productType) {
if (productTypeMaxlength < productType1.length()) {
productTypeMaxlength = productType1.length();
}
}
for(int i=0;i<productType.length;i++)
{
System.out.print(i);
System.out.print("\t");
System.out.print(productId[i]);
System.out.print("\t");
System.out.print(productName[i]);
for(int j=0;j<=productNameMaxlength-productName[i].length
();j++)
{
System.out.print(" ");
}
System.out.print("\t");
System.out.print(productType[i]);
for(int j=0;j<=productTypeMaxlength-productType[i].length
();j++)
{
System.out.print(" ");
}
System.out.print("\t");
System.out.println(productPrice[i]);
}
}
}
and output is--
Sr.No ID NAME TYPE PRICE
0 1001 Cadbury Chocolate 20.0
1 1002 Parker Vector Stationary 150.0
2 1003 Nescafe Coffee 80.0
3 1004 kissan jam Jam 65.0
4 1005 Herbal oil Oil 30.0
5 1006 Garnier man's Face wash 79.0
6 1007 Lays chips chips 10.0
7 1008 biscuits Biscuits 20.0
8 1009 Bournvita Health Supplement 140.0
9 1010 Pepsi Cold Drink 24.0
Since I am unable to answer my question where I have ask my question because of block to ask question and answer I am quoting my answer and this was a different kind of array format I feel.
Upvotes: 3
Reputation: 213203
You can use format()
to format your output according to your need..
for(int i=1; i<13; i++){
for(int j=1; j<13; j++){
System.out.format("%5d", i * j);
}
System.out.println(); // To move to the next line.
}
Or, you can also use: -
System.out.print(String.format("%5d", i * j));
in place of System.out.format
..
Here's is the explanation of how %5d
works: -
%d
which is format specifier for integers..5
in %5d
means the total width your output will take.. So, if your value is 5, it will be printed to cover 5 spaces like this: - ****5
%5d
is used to align right.. For aligning left, you can use %-5d
. For a value 5
, this will print your output as: - 5****
Upvotes: 40