I am new student java learning its basics
My objective is to create a Enum which contains various categories like Emails, Username, Passwords, MaterialType etc.
Further I wanted that within one Category I can declare various strings and my sample code is as below:
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";
}*/
}
}
and I call the code as
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);
}
My question is why on using second string type function it is giving error, example In the password category for GmailPassword() why it is not working.
Is there is any other way to declare multiple strings in enum in category wise manner like
public Enum myEnum{
Category1
{
"String 1","String2",......."String N"
}
.......
.......
.......
.......
CategoryN
{
"String 1","String2",......."String N"
}
maybe this helps?
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];
}
}
Main
public static void main(String[] args) {
System.out.println(MyEnum.Emails); //[mail1, mail2, mail3]
System.out.println(MyEnum.Emails.getString(1)); //mail2
}
You can create an enum with Objects instead of just Strings. That way you can access all the properties of those objects in a clean manner.
It seems to me that instead of an Enum with categories, you should have an interface that you make each category enum implement. That way you have N enums that each implement the category interface, and inside each of those you have the strings as the enum constants.
Related
This question already has answers here:
Generating Enums Dynamically
(4 answers)
Closed 2 years ago.
I'm trying to create an Enumeration in Java. I did a code I created a comboBox with the enum values and it was correct. The problem is that in that case I knew the values I wanted ComboBox to have.
Now I'm trying to create a ComboBox in SceneBuilder with an object characteristic.
I receive from a file a lot of tasks and all of them have it own reference. I want to create an enum with all the references with the objective that user chose one task from the reference in the ComboBox.
Here is the Task code in portuguese (referencia means reference):
//This is a constructor of Tarefa (task):
public Tarefa(String referencia, String designacao, String descricaoInformal, String descricaoTecnica, int duracaoEstimada, Double custoEstimado) {
this.referencia = referencia;
this.designacao = designacao;
this.descricaoInformal = descricaoInformal;
this.descricaoTecnica = descricaoTecnica;
this.duracaoEstimada = duracaoEstimada;
this.custoEstimado = custoEstimado;
}
public String getReferencia() {
return referencia;
}
I was creating other JavaClass creating something like this:
public enum Prioridade {
BAIXA {
public String toString() {
return "Baixa";
}
},
ABAIXO_NORMAL {
public String toString() {
return "Abaixo do Normal";
}
},
NORMAL {
public String toString() {
return "Normal";
}
},
ACIMA_NORMAL {
public String toString() {
return "Acima do Normal";
}
},
ELEVADO {
public String toString() {
return "Elevado";
}
},
TEMPO_REAL {
public String toString() {
return "Tempo Real";
}
};
}
But in that case I knew the values I wanted enum to have.
How can I create an Enum not knowing from the beggining the values it will have? I only know the type: String.
You can use static method of enum valueOf(String str)
For example Prioridade.valueOf("ACIMA_NORMAL")
This is my enmun class
public enum CSSFont {
RezeptName("-fx-font: 22 calibri;"),
RezeptNameClicked("-fx-font: 22 calibri; -fx-underline: true; -fx-text-fill: purple"),
RezeptTab("-fx-font: 15 calibri;");
private String font;
private CSSFont(String s) {
this.font = s;
}
public String getFont() {
return this.font;
}
}
As you can see I created a getFont() function to get the String of each CSSFont object. Is there a way to directly make String objects in an enum class(I need the String for setStyle() methods in JavaFX), so that I don't have to always write CSSFont.object.getFont() but rather CSSFont.object? I tried to let CSSFont extend String, but obviously enums can only implement interfaces. Or is the only solution to create a class with static (final) String attributes?
EDIT: Thanks everybody, it seems I wasn't really sure when to use enums and when not to, since I have only one attribute(String) and I don't even need enumaration or comparison of these enum objects, I will use a class with static final string attributes ;).
You can use something like this:
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Test it using:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
Originally taken from here
You can override toString method:
public enum CSSFont {
RezeptName("-fx-font: 22 calibri;"),
RezeptNameClicked("-fx-font: 22 calibri; -fx-underline: true; -fx-text-fill: purple"),
RezeptTab("-fx-font: 15 calibri;");
private String font;
private CSSFont(String s) {
this.font = s;
}
public String getFont() {
return this.font;
}
public String toString(){
return this.font;
}
}
Then you can get font as follows:
CSSFont.RezeptName.toString()
I have written a code for Person class and in that class create a constructor Person and argument name. Now I have to create an instance of this class will offer a getter for the person's name and also create an instance of this class will respond to a greet method that accepts one argument: message.
When the message is "Hello", greet must return:
Hi, I'm {{name}}
When the message is "Goodbye", greet must return:
Bye
When the message is anything else, greet will return the message that it was provided. I have a tested case code but I am stuck with assertEquals() function and getter function. Now I am facing error with assertfunction. Can anybody please tell me how does assertfucntion and getter works? I have implemented getter in my code, I'm but not sure whether I did it right.
Here's my code:
class Person
{
private String name;
Person(String n)
{
n = name;
}
String GetName()
{
return this.name;
}
public void greet(String t)
{
if (t == "Hello")
{
System.out.println("Hi my name is "+name);
}
else if (t == "Goodbye")
{
System.out.println("bye");
}
else
System.out.println("Hi, my name is"+name);
}
}
Test code:
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.Before;
public class TestPerson {
private Person jeff;
private Person susy;
#Before
public void setup() {
jeff = new Person("Jeff");
susy = new Person("Susy");
}
#Test
public void testGetName() {
assertEquals("Jeff", jeff.GetName());
}
#Test
public void testGreetHelloJeff() {
assertEquals("Hi, I'm Jeff", jeff.greet("Hello"));
}
#Test
public void testGreetHelloSusy() {
assertEquals("Hi, I'm Susy", susy.greet("Hello"));
}
#Test
public void testGreetGoodbye() {
assertEquals("Bye", jeff.greet("Goodbye"));
}
#Test
public void testGreetOther() {
assertEquals("Yo", jeff.greet("Yo"));
}
}
You cannot compare a String and the return value of a method that returns void.
Your Person class is odd. You have it too closely tied to System.out, which is not useful.
Your code has a lot of problems for such a small sample size. Here's what I might suggest:
public class Person {
private String name;
Person(String n) {
this.name = n;
}
String getName() {
return this.name;
}
public String greet(String t) {
if ("Hello".equals(t)) {
return String.format("Hi my name is %s", name);
} else if ("Goodbye".equals(t)) {
return "bye";
} else {
return String.format("Hi, my name is %s", name);
}
}
}
See your method returns void:
public void greet(String t)
How do you expect to get and assert a values of void?
Change void to String and do return a message string.
Also do not use == rather .equals(..)
"Hello" case seems does the same as default. Better do:
public class Person {
private String name;
Person(String name) {
this.name = name;
}
String getName() {
return this.name;
}
public String greet(String m) {
if ("Goodbye".equals(m)) {
return "bye";
} else {
return String.format("Hi, my name is %s", name);
}
}
}
By calling assertEquals("Bye", jeff.greet("Goodbye")); you're comparing the String "Bye" to void since .greet returns void.
Change greet to this:
public String greet(String t){
if(t.equals("Hello"))
return "Hi my name is " + name;
else if(t.equals("Goodbye"))
return "bye";
else
return "Hi, my name is" + name;
}
And then you can use the assertEquals(String, String) like:
assertEquals("bye", jeff.greet("Goodbye"));
In Java when comparing Strings use .equals() instead of ==. So 'if(t=="Hello")"' would be 'if(t.equals("Hello"))'
Method names should start with a lower case letter.
Also String comparison is case sensitive so make sure you are using the correct case when comparing your Strings.
It doesn't make sense to test the greet(String) method using assertEquals, since the method doesn't return anything. The assertEquals is used to assert whether the actual result returned from a tested method is equal to an expected value that you provide, just like the testGetName above.
It seems more appropriate to change void greet(String) to String greet(String) which returns a greeting message according to the t argument to make your code more testable.
Moreover, you should use aStr.equals(bStr) instead of aStr == bStr to compare two String. == just compare the reference of the two String object rather than their values.
enum generalInformation {
NAME {
#Override
public String toString() {
return "Name";
}
},
EDUCATION {
#Override
public String toString() {
return "Education";
}
},
EMAIL {
#Override
public String toString() {
return "Email";
}
},
PROFESSION {
#Override
public String toString() {
return "Profession";
}
},
PHONE {
#Override
public String toString() {
return "Phone";
}
}
}
I have that information are avaiable in enum.
How to print all enum values like: print.generalInformation?
That outputs:
Name
Education
Email
Phone
How to pass that enum generalInformation as an arg in another function?
System.out.println(java.util.Arrays.asList(generalInformation.values()));
Your second part... Just the same as an interface or a class
Firstly, I would refactor your enum to pass the string representation in a constructor parameter. That code is at the bottom.
Now, to print all enum values you'd just use something like:
// Note: enum name changed to comply with Java naming conventions
for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {
System.out.println(info);
}
An alternative to using EnumSet would be to use GeneralInformation.values(), but that means you have to create a new array each time you call it, which feels wasteful to me. Admittedly calling EnumSet.allOf requires a new object each time too... if you're doing this a lot and are concerned about the performance, you could always cache it somewhere.
You can use GeneralInformation just like any other type when it comes to parameters:
public void doSomething(GeneralInformation info) {
// Whatever
}
Called with a value, e.g.
doSomething(GeneralInformation.PHONE);
Refactoring using a constructor parameter
public enum GeneralInformation {
NAME("Name"),
EDUCATION("Education"),
EMAIL("Email"),
PROFESSION("Profession"),
PHONE("Phone");
private final String textRepresentation;
private GeneralInformation(String textRepresentation) {
this.textRepresentation = textRepresentation;
}
#Override public String toString() {
return textRepresentation;
}
}
With your current values, you could actually just convert the name to title case automatically - but that wouldn't be very flexible for the long term, and I think this explicit version is simpler.
Since Java 8 I would suggest the following solution:
public static String printAll() {
return Stream.of(GeneralInformation.values()).
map(GeneralInformation::name).
collect(Collectors.joining(", "));
}
In applications, it's good practice to separate data from presentation. It allows the data to be used in different user interfaces, it makes the data objects more lightweight, and it allows for the future possibility of internationalization.
With that in mind, it's good to avoid strongly coupling the display name to the enum constant. Fortunately, there is a class which makes this easy: EnumMap.
public class ApplicationUI {
private final Map<GeneralInformation, String> names;
public ApplicationUI() {
names = new EnumMap<>(GeneralInformation.class);
names.put(GeneralInformation.NAME, "Name");
names.put(GeneralInformation.EDUCATION, "Education");
names.put(GeneralInformation.EMAIL, "Email");
names.put(GeneralInformation.PROFESSION, "Profession");
names.put(GeneralInformation.PHONE, "Phone");
assert names.keySet().containsAll(
EnumSet.allOf(GeneralInformation.class)) :
"Forgot to add one or more GeneralInformation names";
}
public String getNameFor(GeneralInformation info) {
return names.get(info);
}
}
If you are still on Java 1.7 this is what worked for me:
String genInfoValues = "";
boolean firstRun = true;
for (generalInformation info : generalInformation.values()){
if (firstRun) {
firstRun = false;
genInfoValues += info.name();
} else {
genInfoValues += ", " + info.name();
}
}
values() on the enum returns an array. So, it would be simple to do the following to:
System.out.println(Arrays.toString(generalInformation.values()));
any example of using enum to define a bunch of string consts? The string can contains special charaters like - / etc?
enum MyConstants {
STR1("some text"),
STR2("some other text");
private String value;
private MyConstants(String str) {
this.value = str;
}
public String getValue() {
return value;
}
}
then use it like this:
MyConstants.STR1.getValue();
String [] messages = {"maybe you", "better go with", "an array?"};
System.out.println (messages[1]);
Without further knowledge - why do you like to use enums at all?
I think this page will be helpful:
http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
In short:
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}