String Formatting + Blackberry + java

最后都变了- 提交于 2019-12-08 07:24:29

问题


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;

     }

回答1:


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);
    }
}
  • IdeOne Demo

Update:

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

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




回答2:


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.



来源:https://stackoverflow.com/questions/4612674/string-formatting-blackberry-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!