Whenever I type in a phone number, this program below that I wrote to format phone numbers from the user gives me back weird numbers that I did not even enter at all. Can someone please explain to me why I am getting such weird errors?
I want it so when someone enters just 12345678978 it will format to 1-234-567-8978 If they enter 2345678978 it will format to 234-567-8978 And if they enter 5678978 it will change to 567-8978. I always get weird numbers that sometimes aren't even what I entered like 12345678978 I get 144-34--567- 2345678978 I get 153-567-8978 5678978 I get 162-8978
I would really appreciate some help. Thanks.
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner y = new Scanner(System.in);
String phoneNumber;
int phoneNumberLength;
System.out.print
("Please enter your phone number WITHOUT spaces or dashes: ");
phoneNumber = y.nextLine();
phoneNumberLength = phoneNumber.length();
if (phoneNumberLength == 11) {
phoneNumber = phoneNumber.charAt(0) + "-" + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ phoneNumber.charAt(3)
+ "-" + phoneNumber.charAt(4) + phoneNumber.charAt(5)
+ phoneNumber.charAt(6)
+ "-" + phoneNumber.charAt(7) + phoneNumber.charAt(8)
+ phoneNumber.charAt(9)
+ phoneNumber.charAt(10);
}
if (phoneNumberLength == 7) {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5) + phoneNumber.charAt(6);
}
else {
phoneNumber = phoneNumber.charAt(0) + phoneNumber.charAt(1)
+ phoneNumber.charAt(2)
+ "-" + phoneNumber.charAt(3) + phoneNumber.charAt(4)
+ phoneNumber.charAt(5)
开发者_如何学Go + "-" + phoneNumber.charAt(6) + phoneNumber.charAt(7)
+ phoneNumber.charAt(8)
+ phoneNumber.charAt(9);
}
System.out.println("So your phone number is " + phoneNumber + "?");
}
By the way. I know it is not formatted correctly but I am very confused with how stackoverflow allows you to add code.
Java is converting the characters from your charAt() calls to numerical values. Use substring methods instead, e.g.
phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3);
Any string that starts like this:
number = number.charAt(0) + number.charAt(1) + ...
will cause the problem, because you are adding two char
types together. This is treated as integer arithmetic, not string concatenation. It would be a lot better to add substrings together, so that the operator is string concatenation, instead of integer addition.
number = number.substring(0, 3) + '-' + number.substring(3, 6) + ...
精彩评论