Skip to content
Advertisement

I want to return a formatted Phone Number with use substring but odd thing return

I’m new to java. why this don’t work ?? this must get something like this formatPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) and after that return (123) 456-7890

Thanks for the answers.

public class Program {                                                                             
    public static String formatPhoneNumber(int[] nums) {                                               
        String nums2=nums.toString();
        String a_final ="";
        //"(123) 456-7890"
        a_final="""+("+nums2.substring(0,2)+")"+"t"+nums2.substring(3,5)+"-"+nums2.substring(6,9)+""";
        return a_final; 
                                                                                                 
    }
}

Advertisement

Answer

When using the toString(); method in a primitive type array the result is the location in the memory e.x “[I@1b28cdfa”

If you want to copy your array of numbers in a String just use the StringBuilder

StringBuilder builder = new StringBuilder();

    for (int number : nums){

        builder.append(number);

    }

    String nums2 = builder.toString();

    
    String a_final="("+nums2.substring(0,3)+")"+nums2.substring(3,6)+"-"+nums2.substring(6,9);


    System.out.println(a_final);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement