gpt4 book ai didi

Java 枚举 : Having Multiple Strings within one Enums

转载 作者:行者123 更新时间:2023-12-01 17:05:21 25 4
gpt4 key购买 nike

我是一名java新生,正在学习其基础知识

我的目标是创建一个包含各种类别的枚举,例如电子邮件、用户名、密码、MaterialType 等。此外,我希望在一个类别中我可以声明各种字符串,我的示例代码如下:

public enum MyEnums {
Usernames
{
public String toString()
{
return "This is a GmailUsername";
}
/*public String toString()
{
return "This is a GalleryComment";
}*/
},
Password
{
public String toString()
{
return "This is a public password";
}
/* public String GmailPassword()
{
return "This is a Gmail Password";
} */

},
Emails
{
public String toString()
{
return "This is a public contact email address";
}
/* public String EmailAccount()
{
return "This is a public Email Account address";
} */

},
PhoneNumbers
{
public String toString()
{
return "This is Phonenumber";
}
/* public String Phone()
{
return "This is a phone number";
}*/
}
}

我将代码称为

public static void main (String args[])
{

System.out.println(MyEnums.Emails);
System.out.println(MyEnums.Usernames );
System.out.println(MyEnums.PhoneNumbers);
System.out.println(MyEnums.Password);

}

我的问题是为什么在使用第二个字符串类型函数时会出现错误,例如在 GmailPassword() 的密码类别中为什么它不起作用。

是否有其他方法可以以类别方式在枚举中声明多个字符串,例如

public Enum myEnum{
Category1
{
"String 1","String2",......."String N"
}
.......
.......
.......
.......
CategoryN
{
"String 1","String2",......."String N"
}

最佳答案

也许这有帮助?

 public enum MyEnum {
Emails("mail1", "mail2", "mail3"),
Usernames("username1", "username2"),
CategoryN("a", "b", "c");

private String[] strings;

private MyEnum(String... strings) {
this.strings = strings;
}

@Override
public String toString() {
return Arrays.toString(strings);
}

public String getString(int index) {
return strings[index];
}

}

主要

    public static void main(String[] args) {
System.out.println(MyEnum.Emails); //[mail1, mail2, mail3]

System.out.println(MyEnum.Emails.getString(1)); //mail2
}

关于Java 枚举 : Having Multiple Strings within one Enums,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25807386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com