簡體   English   中英

如何確定字符串中有多少個字符以及字符是否為數字 Java

[英]How to determine how many characters are in a string and if the characters are digits or not Java

我正在為學校做一個客戶信息掃描儀項目,目前我正在處理電話號碼部分。 我需要讓客戶輸入他們的電話號碼,並且我需要檢測盡可能多的錯誤。 這包括:確保都是數字,確保它的十位數字,然后分為 - <區號的3位字符串> <中心局的3位字符串> <站點代碼的4位字符串>最后在之間添加破折號區號、中心局和車站代碼。 有什么簡單的方法可以做到這一點,這是我當前的代碼。 提前致謝

System.out.println(DATA_DIV);
System.out.println("\nCustomer Phone Number Information");
System.out.println("-----------------------------------\n");
System.out.println("Enter the Phone Number:");

phoneNumber = uIn.next();
    
if (phoneNumber.matches("\\d+")) {

} 
else {
    Garbage = uIn.next();
    System.out.println("\n\tError Data Type: you entered ( " + Garbage + " ) for Phone Number");
    System.out.println("Phone Number must be made up of numbers only");
    System.out.println();
    System.out.println("Re-Enter the Phone Number :");
    phoneNumber = uIn.next();
}

我建議您熟悉正則表達式,因為它們在這種情況下非常方便。 我建議您使用的正則表達式: ^(?\d{3})(?\d{3})(?\d{4})$

^ - 表示序列的開始

(?<area/office/code>) - 這就是我們基本上創建一個組並為其命名的方式,以便我們以后需要時可以通過它調用它。

\d - 數字

{3} - 我們正在尋找的前一個元素的確切編號

$ - 序列結束

之后,您應該使用 Pattern 和 Matcher 類來獲得正確的序列,在 Matcher class 中有一些方便的方法,例如 find(groupName)。 我認為在此之后拆分非常簡單。

就個人而言,我不喜歡使用正則表達式來解決這類問題。 如評論中提到的,使用正則表達式的替代方法是從電話號碼的 Backus-Naur 描述構建掃描儀和解析器。 描述如下:

<phone number> ::= <area code>-<central office>-<station code>
<area code> ::= <digit><digit><digit>
<central office> ::= <digit><digit><digit>
<station code> ::= <digit><digit><digit><digit>
<digit> ::= 0|1|2|3|4|5|6|7|8|9

掃描器和解析器如下:

import java.util.Scanner;

public class PhoneNumberParser {
    PhoneNumber number;
    int look;               // Current char read
    int index;              // Index into input buffer
    String input;           // Raw phone number input

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        PhoneNumberParser parser = new PhoneNumberParser();
        try {
            PhoneNumber number = parser.parse(scanner.nextLine());
            System.out.println(number);
        }catch(IllegalArgumentException ex) {
            System.err.println(ex);
        }
    }

    public PhoneNumber parse(String s) throws IllegalArgumentException{
        number = new PhoneNumber();
        input = s;
        index = 0;

        //if( s.length() != 10 )
        //    throw new IllegalArgumentException("Bad phone number. Expected a ten digit number.");

        scan();

        number.areaCode = areaCode();
        scan();
        if( look != '-')
            throw new IllegalArgumentException("Bad phone number. Expected a '-' after the area code.");
        scan();
        number.centralOffice = centralOffice();
        scan();
        if( look != '-')
            throw new IllegalArgumentException("Bad phone number. Expected a '-' after the central office part.");
        scan();
        number.stationCode = stationCode();
        return number;
    }

    private void scan() {
        try {
            look = input.charAt(index++);
        }catch(Exception ex) {
            look = -1;
        }
    }

    private int areaCode() {
        StringBuffer sb = new StringBuffer();
        sb.append(digit());
        scan();
        sb.append(digit());
        scan();
        sb.append(digit());
        return Integer.parseInt(sb.toString());
    }

    private int centralOffice() {
        StringBuffer sb = new StringBuffer();
        sb.append(digit());
        scan();
        sb.append(digit());
        scan();
        sb.append(digit());
        return Integer.parseInt(sb.toString());
    }
    private int stationCode() {
        StringBuffer sb = new StringBuffer();
        sb.append(digit());
        scan();
        sb.append(digit());
        scan();
        sb.append(digit());
        scan();
        sb.append(digit());
        return Integer.parseInt(sb.toString());
    }
    private int digit() {
        if( ! Character.isDigit((char) look) )
            throw new IllegalArgumentException("Bad phone number. Expected a digit, but found a '" + (char)look + "' character.");
        int digit = (char)look - '0';
        return digit;
    }



    class PhoneNumber {
        int areaCode;
        int centralOffice;
        int stationCode;
        public String toString() {
            return "Area code: " + areaCode + " Central office: " + centralOffice + " Station code: " + stationCode;
        }
    }
}

Output 與字符串 999-888-1234 一起提供時是:

Area code: 999 Central office: 888 Station code: 1234

如您所見,掃描儀解析器對錯誤數字的錯誤報告比正則表達式更好,並且還將數字分成其組成部分以供進一步處理。 例如,僅顯示號碼的區號部分可能很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM