Reputation: 1678
I have this Java Enum structure:
public enum ResponseCodes {
ONE("000.200.100", 100, "successfully created checkout"),
TWO("000.200.101", 101, "failed created checkout");
ResponseCodes(String s, int i, String s1) {
}
}
When I receive "000.200.100"
and "successfully created checkout"
I want to get the value 100
. How this check can be implemented?
Upvotes: 0
Views: 64
Reputation: 1053
public enum ResponseCodes {
ONE("000.200.100", 100, "successfully created checkout"),
TWO("000.200.101", 101, "failed created checkout");
private String version;
private String text;
private int code;
ResponseCodes(String s, int i, String s1) {
version = s;
text = s1;
code = i;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
Example:
private int testMethod(){
ResponseCodes example = ResponseCodes.ONE;
if ( example.getVersion().equals( "000.200.100" )
&& example.getText().equals( "successfully created checkout" ) ) {
return example.getCode();
}
return 0;
}
Or get the relevant enum:
private ResponseCodes getResponseCode(){
for ( ResponseCodes c : ResponseCodes.values() ) {
if ( c.getVersion().equals( "000.200.100" )
&& c.getText().equals( "successfully created checkout" ) ) {
return c;
}
}
return ResponseCodes.ONE; // return a default
}
Or follow a different approach:
// change
ONE("000.200.100", 100, "successfully created checkout");
// into
SUCCESSFULLY_CREATED_CHECKOUT_000_200_100(100); // and delete the String fields
//Which makes it possible to pull the int value in this way:
private int testMethod2() {
String text = "successfully created checkout";
String numbers = "000.200.100";
String enumName = (text + " " + numbers).replaceAll("( )|(\\.)", "_" ).toUpperCase();
return ResponseCodes.valueOf(enumName).getCode();
}
Upvotes: 1