String Formatting + Blackberry + java

2019-06-06 00:55发布

I am facing a bit problem with formatting of string. In my application I need to send an email to a web service.The format of the email need to be like this

Name           Class            Section              Position    
Sam            5                A                    1    
Joseph         7                C                    4

For this I have used /n and /t for line breaks ans spacing. But the real problem is with the 'Name' item. The length of 'name' item varies. Currently my approach is that I am taking a reference string sufficiently long and padding blank spaces in each name string until its length is equal to the base String.

The problem that I am facing is that this approach doesn't work fine when I append blank spaces but instead of blank spaces if I append any other character say 'x' then the resulting string is properly formatted.

Function for appending blank spaces :

  private String getModifiedName(String name){
         String testString  = "This is a very big string";

         while(getFont().getAdvance(testString) > getFont().getAdvance(name)){
             name = name + " ";

         }



         return name;

     }

2条回答
我命由我不由天
2楼-- · 2019-06-06 01:25

It seems to me that you try to create an email body that looks well aligned in a viewer. And I guess, you're using a proportional font (like times or helvetica/arial).

Webservices usually don't care if the table looks aligned but care if the message is aligned. Make sure, that the number of chars is each column is the same, even if the result looks ugly on the screen. So really shouldn't use the getFont().getAdvance() method to make Strings (almost) equal size but use String#size() instead for padding.

查看更多
Evening l夕情丶
3楼-- · 2019-06-06 01:32

Try using String.format() if it is there in the version of jdk you are using with blackberry

package org.life.java.so.questions;

/**
 *
 * @author Jigar
 */
public class StringFormatDemo {
    public static void main(String[] args) {
        String name = "Jigar";
        String header = String.format("Name \t Class \t Section \t Positoin");
        String dataRow1 = String.format("%s \t %s \t %s \t %s",name,"A","IT","JavaDev");
        System.out.println(header);
        System.out.println(dataRow1);
    }
}

Update:

As the above method is not there with your java env you can go for

javax.microedition.global.Formatter.formatMessage(...)

查看更多
登录 后发表回答