You are developing a banking module. You have developed a class named ccMask that has a maskcc method.



Given the code fragment:

class CCMask {

    public static String maskCC(String creditCard) {
        String x = "XXXX-XXXX-XXXX-";
        //line n1
    }

    public static void main(String[] args) {
        System.out.println(maskCC("1234-5678-9101-1121"));
    }
}

You must ensure that the maskcc method returns a string that hides all digits of the credit card number except the four last digits (and the hyphens that separate each group of four digits).

Which two code fragments should you use at line n1, independently, to achieve this requirement?

A.

StringBuilder sb = new StringBuilder(creditCard);
sb.substring(15, 19);
return x + sb;
B.
return x + creditCard.substring(15, 19);
C.
StringBuilder sb = new StringBuilder(x);
sb.append(creditCard, 15, 19);
return sb.toString();
D.
StringBuilder sb = new StringBuilder(creditCard);
StringBuilder s = sb.insert(0, x);
return s.toString();

題解

選項A使用到StringBuilder物件的「substring」方法,看似可以,但「substring」方法是直接回傳新的子字串,實際上並不會改變StringBuilder物件本身的內容。因此這樣做沒有辦法輸出我們想要的結果。

選項B解決了選項A的問題。

選項C使用了StringBuilder物件來串接出我們想要的結果。

選項D是直接在原本的creditCard1變數所儲存的字串前直接插入「XXXX-XXXX-XXXX-」,這樣做不是我們想要的結果。