我会从文件加载一个字符串并放入一个对象枚举。
我创建了一个类:
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;
}
在另一个文件中我想读取一个文件并将字符串放入我可以创建对象乘客的方式:
Passenger p=new Passenger(p_name,What should i put here)?
这是我文件的结构:
cod
passenger_name
reverved
鳕鱼和乘客将由String提出,而保留应通过enum提出。我会读到这个文件:
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();
}
答案 0 :(得分:3)
使用YourEnumType.valueOf
将您从文件中读取的String转换为枚举:
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);
}
}
(我冒昧地为您的示例代码制作一个更清晰的版本。)
确保文件中的字符串与枚举常量的名称相同,包括大写字母,并且不包含额外的空格。