Java Enums - 数字add()和分类方法

发布于 2024-09-25 03:14:36 字数 516 浏览 2 评论 0原文

我正在为电话簿创建一个 api,其中包含 3 种不同类型的电话号码:FAX、HOME、WORK、CELL

我想将号码添加到特定类型,但不想将 FAX、HOME、WORK 等分类为原始号码类型,因为我正在考虑以后可以更改它。

我试图使用枚举,但不清楚在这种情况下如何有效地使用它。

到目前为止,我为这部分编写的代码:

private enum NumberType{

FAX, WORK, HOME, CELL}

class PhoneNumber{

 PhoneNumber(int Number, NumberType type){

    this.number = Number;

    this.type = type;
}
..
getter and setter for above
..
}

但我仍然不明白如何将特定的电话号码分配给特定的 NumberType。

我还是很困惑。我想让人们能够轻松地使用此功能。

请帮忙。

谢谢。

I am creating an api for a phonebook which has 3 different types of phone-numbers:FAX, HOME, WORK, CELL

I want to add a number to a specific type but do not want to classify FAX,HOME,WORK etc. as primitive types as I am considering that I could change it at a later date.

I was trying to use enums but am not clear how I can use it efficiently in this case.

The code I worked up till now for this part:

private enum NumberType{

FAX, WORK, HOME, CELL}

class PhoneNumber{

 PhoneNumber(int Number, NumberType type){

    this.number = Number;

    this.type = type;
}
..
getter and setter for above
..
}

But I still do not get how I could assign a specific phoneNumber to a specific NumberType.

I am still confused. I want to make it easy for someone to use this feature.

Please help.

Thank you.

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

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

发布评论

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

评论(2

贩梦商人 2024-10-02 03:14:36

您可以编写一个方法,

NumberType findPhoneNumberType(String phoneNumber)
{
      //logic to differentiate between various types of phone numbers.
      //advantage: you can also check for illegal phone number values.
}

您可以在调用您提到的构造函数之前调用此方法。

NumberType nt = findPhoneNumberType(number);
PhoneNumber phoneNumber = new PhoneNumber(number, nt);

我还建议使用字符串而不是整数来表示电话号码。

You can write a method

NumberType findPhoneNumberType(String phoneNumber)
{
      //logic to differentiate between various types of phone numbers.
      //advantage: you can also check for illegal phone number values.
}

You can call this method before calling the constructor you have mentioned.

NumberType nt = findPhoneNumberType(number);
PhoneNumber phoneNumber = new PhoneNumber(number, nt);

I would also suggest to use Strings rather than ints for phone numbers.

孤君无依 2024-10-02 03:14:36

您只需创建一个新的 PhoneNumber 实例:

PhoneNumber homeNumber = new PhoneNumber(1234567890, NumberType.HOME);

我还建议使用字符串作为电话号码:)

You just have to create a new instance of PhoneNumber :

PhoneNumber homeNumber = new PhoneNumber(1234567890, NumberType.HOME);

I would also suggest to use a String for phone numbers :)

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