質問

Can anyone explain please what is the correct return for this method? Right now I'm missing one.

public String getPhoneNumber() {    
    System.out.println(String.format("+%d(%2$s)%3$s-%4$s-%5$s", 38,
                       String.format("%010d", 501234567).substring(0, 3),
                       String.format("%010d", 501234567).substring(3, 6),
                       String.format("%010d", 501234567).substring(6, 8),
                       String.format("%010d", 501234567).substring(8)));
}
役に立ちましたか?

解決

You're not returning a String, you're just printing one in the default system print stream.

Hence your code will not compile.

return String.format("+%d(%2$s)%3$s-%4$s-%5$s", 38,
                    String.format("%010d", 501234567).substring(0, 3),
                    String.format("%010d", 501234567).substring(3, 6),
                    String.format("%010d", 501234567).substring(6, 8),
                    String.format("%010d", 501234567).substring(8))

他のヒント

try this:

public String getPhoneNumber() {    
    String result = String.format("+%d(%2$s)%3$s-%4$s-%5$s", 38,
        String.format("%010d", 501234567).substring(0, 3),
        String.format("%010d", 501234567).substring(3, 6),
        String.format("%010d", 501234567).substring(6, 8),
        String.format("%010d", 501234567).substring(8));
    System.out.println(result);
    return result;
}

Sure, here is a util class which could do what you want,
execute the main() method to see result.

import java.util.Formatter;

/**
 * <p>
 * Utility for phone number.
 * </p>
 * 
 * @author eric
 * @date Apr 23, 2014 1:09:51 AM
 */
public class PhoneNumberUtil {
    // regular expression for number format
    public static final String NUMBER_FORMAT_REGEX = "+%d(%s)%s-%s-%s";

    /**
     * <p>
     * Format a phone number.
     * </p>
     * 
     * @param originalNumber
     * @param countryCode
     * @return
     */
    public static String getPhoneNumber(int originalNumber, int countryCode) {
        String originalStr = String.format("%010d", originalNumber);

        StringBuffer buf = new StringBuffer();

        Formatter fmt = new Formatter(buf);
        fmt.format(NUMBER_FORMAT_REGEX, countryCode, originalStr.substring(0, 3), originalStr.substring(3, 6), originalStr.substring(6, 8),
                originalStr.substring(8));
        fmt.close();

        return buf.toString();
    }

    public static void main(String[] args) {
        int phoneNumber = 501234567;
        int countryCode = 38;

        String result = PhoneNumberUtil.getPhoneNumber(phoneNumber, countryCode);
        System.out.println(result);
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top