JAVA ONLY public String cleanNumber(String phoneNumber) { int digit=0; String result = ""; String number= ""; for (int i = 0; i < phoneNumber.length(); i++) { char ch = phoneNumber.charAt(i); if (Character.isDigit(ch)) { number = number + ch; digit++; } } if(digit == 10) System.out.println("("+phoneNumber.substring(1,3)+")"+"-"+phoneNumber.substring(4,6)+phoneNumber.substring(7,10)); else result = "Error"; return result; } } Argument "(444) 999-1234" Actual (44)-) 99- "" Expected "(444) 999-1234" "4449991234" (44)-99234 "" "(444) 999-1234" "444.999.1234" (44)-99.12 "" "(444) 999-1234" What am doing wrong? How can I make the actual look like the expected? What do I have to change?
JAVA ONLY
public String cleanNumber(String phoneNumber)
{
int digit=0;
String result = "";
String number= "";
for (int i = 0; i < phoneNumber.length(); i++)
{
char ch = phoneNumber.charAt(i);
if (Character.isDigit(ch))
{
number = number + ch;
digit++;
}
}
if(digit == 10)
System.out.println("("+phoneNumber.substring(1,3)+")"+"-"+phoneNumber.substring(4,6)+phoneNumber.substring(7,10));
else
result = "Error";
return result;
}
}
Argument "(444) 999-1234" |
Actual (44)-) 99- "" |
Expected "(444) 999-1234" |
"4449991234" | (44)-99234 "" | "(444) 999-1234" |
"444.999.1234" | (44)-99.12 "" | "(444) 999-1234" |
What am doing wrong? How can I make the actual look like the expected? What do I have to change?

Here in the code, we have the method named cleanNumber().
Inside this method all the logic written is correct, but while forming the final string we have used the number passed as a parameter instead of using the number which has been cleaned.
So, I have changed the variable to a number while forming the result, and also in the substring method, I have decremented the start range by one.
Next, instead of printing the result inside the method, I have stored it in another string and returned it.
Then, in the main method, I have called the function inside the print statement to display the result on the console.
Step by step
Solved in 2 steps with 1 images









