Home > Back-end >  Java Justify text in string to far left/start and far right/end and leave space in the middle
Java Justify text in string to far left/start and far right/end and leave space in the middle

Time:12-18

I am having a string in java that i am printing and has title and amount for example below


Rice Ksh 150
Cooking Oil Ksh 200
Skinless White Meat Ksh 450
Honey Ksh 270
Cottage Cheese Ksh 539

What i would like to achieve when i print is something like this below


Rice                Ksh 150
Cooking Oil         Ksh 200
Skinless White Meat Ksh 450
Honey               Ksh 270
Cottage Cheese      Ksh 539

Below is what i have tried but its not working is there another function that i can use to make the output justified where title of the items is far left/start and amount is far right/end


for (Receipt receipt : receiptList) {


        String output = "";

        String itemAmount = String.format("%s %s %s", receipt.getItem(),
                    "Ksh", receipt.getAmount());

        for (int i = 0; i < itemAmount.length(); i  ){
            char c = itemAmount.charAt(i);
            if (c==' '){
                output  = " ";
            }else {
                output  = ""   c;
            }
        }

        // print output here

}

CodePudding user response:

    List<Receipt> receiptList = asList(
            new Receipt("Rice Ksh", 150),
            new Receipt("Skinless White Meat Ksh", 150),
            new Receipt("Cottage Cheese Ksh", 150));
    int maxSize = 0;
    for (Receipt receipt : receiptList) {
        if(receipt.getItem().length()>maxSize)
            maxSize = receipt.getItem().length();
    }
    for (Receipt receipt : receiptList) {
        int spaces = maxSize 1 - receipt.item.length();
        String s = String.format("%1$" spaces "s", "");
        System.out.println(receipt.item.substring(0,receipt.item.length()-3)   s   " KSH "   receipt.amount );
    }

OUTPUT:

Rice                  KSH 150
Skinless White Meat   KSH 150
Cottage Cheese        KSH 150

performance log(n).

CodePudding user response:

I would use System.out.printf and specify the width of each column.

Example:

String[] item = {"Rice", "Cooking Oil", "Skinless White Meat", "Honey", "Cottage Cheese"};
int[] amount = {150,200,450,270,539};
        
for(int i=0; i<item.length; i  )
  System.out.printf("%-20s%4sM\n", item[i],"Ksh", amount[i]);

Output:

Rice                 Ksh 150
Cooking Oil          Ksh 200
Skinless White Meat  Ksh 450
Honey                Ksh 270
Cottage Cheese       Ksh 539
  • Related