Mazzy
Mazzy

Reputation: 14229

load from a file object Enum

I would load from a file a string and put in in a object enum.

I create into a class this:

public Passenger{

private String pass_name;
public enum State{

b,c,d;

};
....

State reser;

public Passenger(String n,State r)
      pass_name=n;
      reser=r;
}

in another file I want read a file and put the string in the way i can create an object passenger such:

Passenger p=new Passenger(p_name,What should i put here)?

here is the structure of my file:

cod
passenger_name
reverved

cod and passenger will be rapresented by String while reserved should be rapresented through enum. I will read the file:

 BufferedReader reader=new BufferedReader(new FileReader(fname));

 String cod=reader.readLine();
 while(cod!=null){
      String p_name=reader.readLine();
      how can i load a enum type?

      Passenger p=new Passenger(p_name,What should i put here)?
      cod=reader.readLine();

 }

Upvotes: 3

Views: 4577

Answers (1)

millimoose
millimoose

Reputation: 39980

Use YourEnumType.valueOf to convert the String you read from the file into the enum:

public class Passenger {
    public static enum State {
        New,
        Reserved,
        Paid
    }

    private String name;
    public State state;

    public Passenger(String name, State state){
        this.name = name;
        this.state = state;
    }

    public String toString() {
        return String.format("Passenger{name='%s', state=%s}", name, state.name());
    }
}

class Main {
    public static void main(String[] args) {
        // line read from file
        String stateString = "Reserved";
        // convert string into state
        Passenger.State state = Passenger.State.valueOf(stateString);

        // create the passenger
        Passenger pass = new Passenger("John Doe", state);
        System.out.println(pass);
    }
}

(I took the liberty of making a cleaner version of your sample code.)

Make sure that the string in the file is the same as the name of your enum constant, including capitals, and that it doesn't include extra whitespace.

Upvotes: 4

Related Questions