4

I would like to use enum as a way of switching over strings, however java complains as my string contains "-". As seen in the code below where IC19-01 and IC19-02 contain "-".

public class CMain {
    public enum Model {
        IC19-01, IC19-02
    }

    public static void main(String[] args){
        String st = "IC19-01"; 
        switch (Model.valueOf(st)) {
            case IC19-01: 
                System.out.println("Case IC19-01");
                break;
        }
    }
}

What can i do for this?

Barney
  • 2,273
  • 3
  • 20
  • 37
C graphics
  • 6,750
  • 18
  • 75
  • 124

3 Answers3

5

This is not possible with Java, because each item has to be a valid identifier (and valid Java identifiers may not contain dashes).

joan
  • 2,145
  • 2
  • 22
  • 27
3

This is not possible in Java as is. But you could do your own implementation as a work around, although it will yield more code. You could change your enum like the following:

 public enum Model {
    IC19_01("IC19-01"), 
    IC19_02("IC19-02")

    private final String name;

    private Model(String name){
     this.name = name;
    }

    public String getName(){
       return name;
    }

   public static Model getByName(String aName){
         for(Model current: Model.values()){
           if(current.getName().equalsIgnoreCase(aName.trim())){
              return current;
           }
          }
          return null;
    }
}

Then you should be able to call Model.getByName(st) instead of Model.valueOf. Alternatively, in Java 7 you should be able to switch the actual String.

Sednus
  • 2,067
  • 1
  • 18
  • 34
  • this solution will never work (current.equalsIgnoreCase doesn't exist) – treaz Nov 24 '17 at 09:02
  • 1
    equalsIgnoreCase is a method from String, it was intended to get name of current before the check. Edited to reflect that change – Sednus Nov 28 '17 at 15:20
0

Blockquote

Enums are classes and should follow the conventions for classes. Instances of an enum are constants and should follow the conventions for constants.

Blockquote

Details about this can be found on following link

Coding Conventions - Naming Enums Hope it helps

Community
  • 1
  • 1
Jabir
  • 2,578
  • 1
  • 19
  • 29