我想驗證用戶輸入的電話號碼,我需要做的第一件事是檢查,以確保輸入字符串的長度是10哪個是這是您在代碼中看到的問題。java驗證字符串包含數字和搜索,以確保沒有字符
現在是問題出現的地方,我還需要檢查以確保沒有輸入字符,以及有關如何在不使用數組的情況下執行此操作的任何想法。我想使用Character.isLetter();但無論我如何實施它,它都不是正確的。
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isNumber = false;
String phoneNum = "";
Scanner input = new Scanner(System.in);
while(!isNumber)
{
System.out.print("\nEnter your 10 digit phone number (ex: 2123345657): ");
phoneNum = input.nextLine();
/* Yes I could use nextInt(); etc.. but that would defeat the
purpose of this exercise */
if(phoneNum.length() != 10)
{
System.out.println("\n\nBad input");
}
else
isNumber = true;
}
System.out.println("\n\nPhone number is: " + phoneNum);
}
}
我在找這樣的事情。
while(!isRight)
{
System.out.print("\n input number: ");
phoneNum = input.nextLine();
while(i < phoneNum.length())
{
if(phoneNum.length() != 10)
{
System.out.println("not enough numbers");
}
else if (Character.isLetter(phoneNum.charAt(i)) == true)
{
System.out.println("Sorry you can't use any thing but numbers");
}
else
isRight = true;
i++;
}
}
爲什麼不''[0-9] {10}'? –
@AndyTurner因爲我的咖啡機今天早上壞了 –
是的,我可以這樣做,我曾經希望使用Character.isLetter()方法的一些東西。我似乎無法正確實施。 – Afflicted