简体   繁体   English

如何确定字符串中有多少个字符以及字符是否为数字 Java

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

I am doing a customer information scanner project for school, currently I am working on the phone number portion.我正在为学校做一个客户信息扫描仪项目,目前我正在处理电话号码部分。 I need to have the customer enter their phone number and I need to detect as many errors as possible.我需要让客户输入他们的电话号码,并且我需要检测尽可能多的错误。 This includes: make sure it's all digits, make sure its ten digits, then to divide into - <3 digit String for Area Code> <3 digit String for Central Office > <4 digit String for Station Code> and finally add dashes between the area code, central office, and station code.这包括:确保都是数字,确保它的十位数字,然后分为 - <区号的3位字符串> <中心局的3位字符串> <站点代码的4位字符串>最后在之间添加破折号区号、中心局和车站代码。 Are there any easy ways to do this, here is my current code.有什么简单的方法可以做到这一点,这是我当前的代码。 Thanks in advance提前致谢

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();
}

I would suggest you get familiar with regular expressions as they come really handy in situations like this one.我建议您熟悉正则表达式,因为它们在这种情况下非常方便。 The regex I would suggest you use: ^(?\d{3})(?\d{3})(?\d{4})$我建议您使用的正则表达式: ^(?\d{3})(?\d{3})(?\d{4})$

^ - means start of the sequence ^ - 表示序列的开始

(?<area/office/code>) - that's how we basically create a group and give it a name so we can call it by it later when we need it. (?<area/office/code>) - 这就是我们基本上创建一个组并为其命名的方式,以便我们以后需要时可以通过它调用它。

\d - digit \d - 数字

{3} - the exact number of the preceding element we're looking for {3} - 我们正在寻找的前一个元素的确切编号

$ - end of sequence $ - 序列结束

After that you should use the Pattern and Matcher classes in order to get the right sequences, there are handy methods like find(groupName) in the Matcher class.之后,您应该使用 Pattern 和 Matcher 类来获得正确的序列,在 Matcher class 中有一些方便的方法,例如 find(groupName)。 I think splitting is quite straightforward after this.我认为在此之后拆分非常简单。

Personally, I don't like using regex to solve this kind of problem.就个人而言,我不喜欢使用正则表达式来解决这类问题。 The alternative to using regex as mentioned in the comments is to build a scanner and parser from a Backus-Naur description for a phone number.如评论中提到的,使用正则表达式的替代方法是从电话号码的 Backus-Naur 描述构建扫描仪和解析器。 The description appears below:描述如下:

<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

The scanner and parser is as follows:扫描器和解析器如下:

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 when supplied with the string 999-888-1234 is: Output 与字符串 999-888-1234 一起提供时是:

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

As you can see, the scanner parser gives better error reporting for bad numbers than regexp and also separates out the number into its constituent parts for further processing.如您所见,扫描仪解析器对错误数字的错误报告比正则表达式更好,并且还将数字分成其组成部分以供进一步处理。 For example, it may be important to just display the area code portion of the number.例如,仅显示号码的区号部分可能很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM