我试图写一个程序来检查输入是否是电话号码格式,所以(555)555-5555,555-555-5555或555-5555。我已经编写了一个程序,但无论我使用什么输入,它总是说它是不正确的。如何让它识别正确的输入?我认为问题是它只检查i的值,如何检查整个输入值?
import java.util.Scanner;
public class ValidPhoneNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i;
String format;
String[] value;
int[] number;
value = new String[10];
number = new int[10];
i = 0;
System.out.println("Please enter a phone number: ");
value[i] = input.nextLine();
if (value[i].matches("([0 - 9]{3})[0 - 9]{3} - [0 - 9]{4}"))
System.out.println("Correct format");
if (value[i].matches("[0 - 9]{3} - [0 - 9]{3} - [0 - 9]{4}"))
System.out.println("Correct format");
if (value[i].matches("[0 - 9]{3} - [0 - 9]{4}"))
System.out.println("Correct format");
else
System.out.println("Not the correct format");
}
}