使用String builder和split更改java电话格式

问题描述 投票:0回答:1

我试图通过首先在中间拆分点,然后检查其输入是否有效以及是否为+1(204)867-5309,将字符串电话号码重新格式化为throw new IllegalArgumentException。但是由于某种原因,即使我使用“字符串”构建器进行更改,数字的输出也不会更改。提前致谢。

public class format{
    public static void main (String[] args){
        String phone = "204.867.5309"; 
        System.out.println(format(phone));
    }

    public static String format(String phone){
        char [] phoneLine = phone.toCharArray(); 
        String [] split = phone.split("\\."); 

        for (char c: phoneLine){
            if (phoneLine[3]=='.'
            && phoneLine[7]=='.'
            && phoneLine.length == 12 
            && Character.isDigit(phoneLine[1])
            && Character.isDigit(phoneLine[0])
            && Character.isDigit(phoneLine[2])
            && Character.isDigit(phoneLine[4])
            && Character.isDigit(phoneLine[5])
            && Character.isDigit(phoneLine[6])
            && Character.isDigit(phoneLine[8])
            && Character.isDigit(phoneLine[9]))
            {  
                StringBuilder sb = new StringBuilder(phone); 
                sb.append("+1");
                sb.insert(2,"("); 
                sb.insert(6, ")");
                sb.insert(10,"-");
            }
            else {
                throw new IllegalArgumentException("not valid"); 
            }
        }
        return phone; 
    }
}
java arrays string builder
1个回答
0
投票

您可以尝试以下code.output:20(48)67-5309 + 1

    public class PhoneNumberFormat {
    public static void main (String[] args){
        String phone = "204.867.5309";
        System.out.println(format(phone));
    }

    public static String format(String phone){
        char [] phoneLine = phone.toCharArray();
        String [] split = phone.split("\\.");
        StringBuilder sb=new StringBuilder();
        for (char c: phoneLine){
            if (phoneLine[3]=='.'
                    && phoneLine[7]=='.'
                    && phoneLine.length == 12
                    && Character.isDigit(phoneLine[1])
                    && Character.isDigit(phoneLine[0])
                    && Character.isDigit(phoneLine[2])
                    && Character.isDigit(phoneLine[4])
                    && Character.isDigit(phoneLine[5])
                    && Character.isDigit(phoneLine[6])
                    && Character.isDigit(phoneLine[8])
                    && Character.isDigit(phoneLine[9]))
            {
                sb = new StringBuilder(phone);
                sb.append("+1");
                sb.insert(2,"(");
                sb.insert(6, ")");
                sb.insert(10,"-");
            }
            else {
                throw new IllegalArgumentException("not valid");
            }
        }
        return sb.toString().replace(".","");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.