表示电话号码的正确方法是什么?

发布于 2024-09-14 04:41:47 字数 140 浏览 10 评论 0原文

我在我的一个应用程序中表示手机号码时遇到问题。

我想知道是否有一个 Integer 类允许您存储以 0417254482 开头的数字。也许使用字符串更合适? 目前,当我尝试使用整数、双长整数表示电话号码时,我似乎存储了随机数,而不是我想要存储的数字。

I'm having trouble representing a mobile number in one of my applications.

I was wondering if there is an Integer class that will allow you to store such a number starting with 0417254482. Perhaps using a string be a more appropriate?
At present when I'm trying to use represent a phone number with ints, doubles longs I seem to store random numbers and not the numbers I meant to store.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

肥爪爪 2024-09-21 04:41:47

使用字符串。除此之外,如果使用整数,您将无法存储前导零。您绝对不应该使用int(太小)floatdouble(数据丢失的风险太大 -见下文); longBigInteger 可能是合适的(除了前导零问题),但坦率地说,我会选择 String。这样,如果您愿意,您还可以存储用户输入的任何破折号或空格,以便更容易记住该数字。

就上面提到的 floatdouble 的“数据丢失”而言 - float 肯定没有足够的精度; double 可以工作,如果你很高兴你永远不需要超过 16 位数字(比使用 long 得到的数字少几个),但是您需要非常非常小心,无论在哪里将值从 double 转换回 string,您都会获得准确的值。许多格式转换将为您提供一个近似值,该近似值可能精确到 10 位有效数字 - 但您需要一个精确的整数。基本上,对电话号码使用浮点是一个根本上的坏主意。如果您必须使用固定宽度的数字类型,请使用long,但理想情况下,完全避免使用它。

Use String. Aside from anything else, you won't be able to store leading zeroes if you use integers. You definitely shouldn't use int (too small) float or double (too much risk of data loss - see below); long or BigInteger could be appropriate (aside from the leading zeroes problem), but frankly I'd go with String. That way you can also store whatever dashes or spaces the user has entered to make it easier to remember the number, if you want to.

In terms of the "data loss" mentioned above for float and double - float definitely doesn't have enough precision; double could work if you're happy that you'll never need more than 16 digits (a couple fewer than you get with long) but you would need to be very, very careful that anywhere you convert the value back from double to string, you got the exact value. Many formatting conversions will give you an approximation which may be accurate to, say, 10 significant digits - but you'd want an exact integer. Basically, using floating point for phone numbers is a fundamentally bad idea. If you have to use a fixed-width numeric type, use a long, but ideally, avoid it entirely.

自找没趣 2024-09-21 04:41:47

想一想:电话号码真的是一个数字吗?与电话号码相加(或进行其他算术运算)是否有意义?电话号码是代码,它们通常用数字表示,但这只是一种约定,也许在另一个国家也使用字母(我刚刚意识到,国际电话号码怎么样?它们有一个 +< /code> 开头。
你必须思考你想要表现的事物的本质,然后找到最合适的表现形式。

Think about this: Is a phone number really a number? Does it make sense adding (or make another arithmetic operation) with phone numbers? Phone numbers are codes, they're usually represented with numbers, but that's just a convention and, maybe, in another country the use letters too (I've just realized, what about international phone numbers? they have a + at the beginning.
You have to think about the nature of the things you want to represent, and then, find the most suitable representation.

甜味超标? 2024-09-21 04:41:47

如果您想进行验证和规范化,您可能需要依赖一个可以正确完成此操作的库。 https://github.com/googlei18n/libphonenumber 是最常见的选项之一。

If you want to do validation and normalization you probably want to rely on a library that does it properly for you. https://github.com/googlei18n/libphonenumber is one of the most common options.

芸娘子的小脾气 2024-09-21 04:41:47

尽管电话号码是命名号码,但它们通常不是数字(例如前导零、国家/地区前缀+XX,...)。

因此,在程序中正确表示电话号码有两种可能性:

  1. 使​​用 String 来保留输入的整个号码。
  2. 使用自定义数据类型为电话号码功能提供额外支持

    公共类 PhoneNumber 实现 Comparable{
    
        私有字符串国家代码;
    
        私有字符串区域代码;
    
        私有字符串订阅者编号;
    
        // 构造函数
    
        // 吸气剂
    
        // 哈希码+等于
    
        // 比较
    
        @覆盖
        公共字符串 toString(){
            返回国家代码 + " " + 地区代码 + " " + 订阅者号码;
        }
    }
    

查看所有不同的国际通用的惯例

Although phone numbers are named numbers, they are normally not numbers (e.g. leading zeros, country prefix +XX, ...).

So there are two possibilities to represent a phone number correctly inside a program:

  1. Using String to keep the whole number like entered.
  2. Using a custom data type that offers additional support for phone number features

    public class PhoneNumber implements Comparable<PhoneNumber>{
    
        private String countryCode;
    
        private String areaCode;
    
        private String subscriberNumber;
    
        // Constructor(s)
    
        // Getter
    
        // HashCode + Equals
    
        // compareTo
    
        @Override
        public String toString(){
            return countrycode + " " + areaCode + " " + subscriberNumber;
        }
    }
    

It's really interesting to look at all the different conventions that are used internationally

颜漓半夏 2024-09-21 04:41:47

创建您自己的 PhoneNumber 类,并使用 String 类型的私有字段来表示它。

public class PhoneNumber {
   private String number;
   public PhoneNumber(String number) {
      //check validity of number
      this.number = number;
   }
   //getter, comparator, etc...
}

如果所有电话号码的长度相同,您也可以用 long 或 BigInteger 表示号码,但要小心前导零。

电话号码实际上并不是整数(或字符串)。它是别的东西,应该有自己的一类。

编辑:
还有一件事:我不会为此类实现 setter,因为电话号码对象最好是不可变的

Create your own PhoneNumber class with a private field of type String to represent it.

public class PhoneNumber {
   private String number;
   public PhoneNumber(String number) {
      //check validity of number
      this.number = number;
   }
   //getter, comparator, etc...
}

You could also represnt the number with long or BigInteger if all phone numbers have the same length, but be careful with leading zeros.

A phone number is not really an integer (or a string). It is something else which shuld have a class of its own.

EDIT:
one more thing: I wouldn't implement a setter for this class because a phone number object would better be immutable

謌踐踏愛綪 2024-09-21 04:41:47

您应该使用字符串或更专业的数据结构。

主要原因是您可以对电话号码执行的操作是字典顺序的,而不是算术运算。
例如,您可以说法国的电话号码以 +33 开头,但您不能假设它们在数字范围内。

我认为这些其他参数无效

  • 电话号码可以包含 *#。这些符号可以在电话线上传输,但它们不是电话号码本身的一部分,我认为它超出了范围。
  • 电话号码可以以前导零开头。本地电话号码可以,但首先它们的代表性有限。国际电话号码以国家/地区代码开头,并且没有一个前导零。因此,国际电话号码都没有前导零。
  • 电话号码以 + 开头。一个简单的正数就可以完美地代表这一点。另外以+开头只是E164号码的表示,以便与本地号码区分开来。如果您只操作 E164 数字,那么他们实际上不必这样做。
  • 电话号码可以包含空格或括号。这是荒谬的,因为它只是数字的文本表示。您不应该存储此信息,因为人们可能有不同的个人偏好来分隔数字组(.- 等)。

You should use a string or a more specialized data structure.

The main reason is that the operations that you can do on phone numbers are lexicographic, and not arithmetic.
e.g. You can say that phone numbers for France start with +33, but you cannot assume they are in a numerical range.

These other arguments are not valid in my opinion

  • a phone number can include * or #. This symbols can be transported on phone lines, but they are not part of the phone number itself, and I consider it's out of scope.
  • a phone number can start with leading zeros. Local phone numbers can, but they are a limited representation in the first place. International phone numbers start with a country code, and none of them has a leading zero. Hence no international phone number has leading zeros.
  • a phone number starts with +. A number can perfectly represent this, by simply being positive. Also starting with + is just a representation of E164 numbers, so that they can be distinguished from local numbers. They really don't have to, if you only manipulate E164 numbers.
  • a phone number can contain spaces or parentheses. This is absurd, because it's just textual representation of the number. You shouldn't store this as people can have different personal preferences to separate groups of digits (., -, , etc.).
深爱不及久伴 2024-09-21 04:41:47

您应该使用字符串来支持带有前导零的数字。您提供的代码是:

Order order1 = new PickUpOrder(orderTime, 0473519954); 
//The pickup order requires an orderTime (String) and a contact number(Int). Heres    
//the constructor for PickUpOrder. 

public PickUpOrder(Date orderTime, String number) 
{ 
    discount = .2; 
    phoneNumber = number; 
    super.setOrderTime(orderTime); 
    //Test print 
    System.out.println(phoneNumber) 
    //reads int as 74049273 instead of 0473519954 
}

在构造函数中,数字是字符串,但是当您调用构造函数时,您使用了 int 来表示电话号码。我认为java中一定有编译错误。这和你编译的代码是一样的吗?

You should use string to support numbers with leading zeros. The code you provided was:

Order order1 = new PickUpOrder(orderTime, 0473519954); 
//The pickup order requires an orderTime (String) and a contact number(Int). Heres    
//the constructor for PickUpOrder. 

public PickUpOrder(Date orderTime, String number) 
{ 
    discount = .2; 
    phoneNumber = number; 
    super.setOrderTime(orderTime); 
    //Test print 
    System.out.println(phoneNumber) 
    //reads int as 74049273 instead of 0473519954 
}

In the constructor, the number is string but when you call the constructor you used an int for phone number. There must have been a compile error here in java I think. Is this the same code you compiled?

天冷不及心凉 2024-09-21 04:41:47

每个数字的左侧和右侧都有无穷多个零,

要表示它,您应该使用字符串格式

class PhoneNumber implements Comparable<PhoneNumber> {

    private Long number;

    public PhoneNumber(Long number) {
        this.number = number;
    }

    public Long getNumber() {
        return this.number;
    }

    public boolean equals(Object object) {

        if (getNumber() == null && object == null) {
            return true; //or false its depend 
        }

        return getNumber().equals(object);
    }

    public int compareTo(PhoneNumber that) {

            if(that == null) {
             return -1;
            }

        Long thisNumber = getNumber();
            Long thatNumber = that.getNumber();

        if (thisNumber == null && thatNumber == null) {
            return 0; //or -1
        }

        if (thisNumber == null && thatNumber != null) {
            return -1;
        }

        return thisNumber.compareTo(thatNumber);

    }

    @Override
    public String toString() {
        return String.format("%010d", getNumber());
    }
}

使用 %010d 表示
%[argument_index$][flags][width][. precision]转换

标志 0 - 填充零
10 - 填充零的数量
d - 十进制整数

Comparable 接口的实现使您可以对 List 进行排序。

List<PhoneNumber> phoneNumbers = new ArrayList();
 phoneNumbers.add(new PhoneNumber (123L);
 phoneNumbers.add(new PhoneNumber (123777L);
 phoneNumbers.add(new PhoneNumber (125L);
 phoneNumbers.add(new PhoneNumber (124L);
 phoneNumbers.add(new PhoneNumber (126L);

Collections.sort(phoneNumbers);

  for(PhoneNumber phoneNumber : phoneNumbers) {
   System.Console.Out.WriteLine(phoneNumber);
  }

输出是

 0000000000 
 0000000123
 0000000124
 0000000125
 0000000126
 0000123777

可比较
字符串格式化程序

Every number have infinity amount of zeros on the left and right side,

To represent it you should use a string formating

class PhoneNumber implements Comparable<PhoneNumber> {

    private Long number;

    public PhoneNumber(Long number) {
        this.number = number;
    }

    public Long getNumber() {
        return this.number;
    }

    public boolean equals(Object object) {

        if (getNumber() == null && object == null) {
            return true; //or false its depend 
        }

        return getNumber().equals(object);
    }

    public int compareTo(PhoneNumber that) {

            if(that == null) {
             return -1;
            }

        Long thisNumber = getNumber();
            Long thatNumber = that.getNumber();

        if (thisNumber == null && thatNumber == null) {
            return 0; //or -1
        }

        if (thisNumber == null && thatNumber != null) {
            return -1;
        }

        return thisNumber.compareTo(thatNumber);

    }

    @Override
    public String toString() {
        return String.format("%010d", getNumber());
    }
}

Used %010d mean
%[argument_index$][flags][width][.precision]conversion

flag 0 - padding zeros
10 - amount of padding zeros
d - decimal integer

The implementation of interface Comparable give you the posibility to sort List.

List<PhoneNumber> phoneNumbers = new ArrayList();
 phoneNumbers.add(new PhoneNumber (123L);
 phoneNumbers.add(new PhoneNumber (123777L);
 phoneNumbers.add(new PhoneNumber (125L);
 phoneNumbers.add(new PhoneNumber (124L);
 phoneNumbers.add(new PhoneNumber (126L);

Collections.sort(phoneNumbers);

  for(PhoneNumber phoneNumber : phoneNumbers) {
   System.Console.Out.WriteLine(phoneNumber);
  }

The output is

 0000000000 
 0000000123
 0000000124
 0000000125
 0000000126
 0000123777

Comparable
String Formatter

孤独陪着我 2024-09-21 04:41:47

我建议不要使用原始数据类型。

原因:基元不能接受特殊字符,例如+、-、(、、)。如果您接受此格式的电话号码+1(xxx)-xxx-xxxx

I would suggest not use primitive data type.

Reason: Primitives cannot accept special characters such as +,-,(, and, ). If you accept phone numbers in this format +1(xxx)-xxx-xxxx.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文