Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Formatter in GWT

Tags:

java

gwt

How do I format my string in GWT?

I made a method

  Formatter format = new Formatter();
    int matches = 0;
    Formatter formattedString = format.format("%d numbers(s, args) in correct position", matches);
    return formattedString.toString();

But it complains by saying

Validating newly compiled units
   [ERROR] Errors in 'file:/C:/Documents%20and%20Settings/kkshetri/workspace/MasterMind/MasterMind/src/com/kunjan/MasterMind/client/MasterMind.java'
      [ERROR] Line 84: No source code is available for type java.util.Formatter; did you forget to inherit a required module?

Isn't Formatter included?

like image 926
unj2 Avatar asked Jun 27 '10 03:06

unj2


4 Answers

See the official page on GWT date and number formatting.

They suggest the following:

myNum decimal = 33.23232;
myString = NumberFormat.getFormat("#.00").format(decimal);

It is best to use their supported, optimized methods, than to cook up your own non-optimal method. Their compiler will be optimizing them all to nearly the same thing anyway in the end.

like image 174
Joseph Lust Avatar answered Oct 24 '22 02:10

Joseph Lust


A very simple replacement for String.format() in GWT 2.1+:

import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;

public static String format(final String format, final Object... args) {
  final RegExp regex = RegExp.compile("%[a-z]");
  final SplitResult split = regex.split(format);
  final StringBuffer msg = new StringBuffer();
  for (int pos = 0; pos < split.length() - 1; ++pos) {
    msg.append(split.get(pos));
    msg.append(args[pos].toString());
  }
  msg.append(split.get(split.length() - 1));
  return msg.toString();
}
like image 37
yegor256 Avatar answered Oct 24 '22 04:10

yegor256


UPDATE: Please see (and vote up) Joseph Lust's post below before looking further at this answer.

Looks like formatter isn't included according to this post. However, they suggest some alternatives.

like image 21
Pace Avatar answered Oct 24 '22 02:10

Pace


Or even simpler, not using RegExp, and using only Strings:

public static String format(final String format, final String... args) {
    String[] split = format.split("%s");
    final StringBuffer msg = new StringBuffer();
    for (int pos = 0; pos < split.length - 1; pos += 1) {
        msg.append(split[pos]);
        msg.append(args[pos]);
    }
    msg.append(split[split.length - 1]);
    return msg.toString();
 }
like image 5
ka2 Avatar answered Oct 24 '22 02:10

ka2