英文:
how to make a map of properties using formatted string "Property:Value"
问题
让我们假设我们创建了一个格式化的字符串,类似这样:"Property:Value"。在Java中,如何将这个格式化的字符串放入一个HashMap<JoystickEnum, String>
中,其中Property
是一个enum
,而值是一个string
。目前我正在一个项目中工作,我们使用这种格式化的字符串接收输入。我的enum
叫做JoystickEnum
。这个类叫做Joystick
,它扩展了Controller类。注意:由于我们将在多个控制器中实现这个抽象类,所以这个类有以下代码,
public String data;
public InputStream dataStream;
private byte[] readBuffer = new byte[400];
public enum InputMode {
POLL, EVENT
};
public InputMode mode = InputMode.EVENT;
public InputHandler(InputStream dataStream) {
this.dataStream = dataStream;
}
@Override
public abstract void serialEvent(SerialPortEvent arg0);
public void setDataMode(InputMode mode) {
this.mode = mode;
}
public abstract void poll();
public abstract Map getData();
@Override
public abstract void run();
InputMode
枚举只包含POLL, EVENT
。代码将放在扩展方法getData()
中。
英文:
Lets say we created a string formatted like this "Property:Value". How do we put this formatted string into a map in Java like this HashMap<JoystickEnum,String>
where Property
is an enum
and the value is a string
. Currently I am working on a project where we recieve input using this formatted string. My enum is called JoystickEnum
. The class is called Joystick
and it extends the Controller class.NOTE: Since we will be using this abstract class that is going to be implemented in multiple controllers. This class has code,
public String data;
public InputStream dataStream;
private byte[] readBuffer = new byte[400];
public enum InputMode {
POLL,EVENT
};
public InputMode mode = InputMode.EVENT;
public InputHandler(InputStream dataStream) {
this.dataStream = dataStream;
}
@Override
public abstract void serialEvent(SerialPortEvent arg0);
public void setDataMode(InputMode mode) {
this.mode = mode;
}
public abstract void poll();
public abstract Map getData();
@Override
public abstract void run();
// TODO Auto-generated method stub
The InputMode
enum just contains POLL,EVENT
. Where the code will go is in the extended method getData()
答案1
得分: 0
如果data是格式为"Property:Value"的字符串,而map是类型为Map<JoystickEnum,String>的对象,则您可以按以下方式添加条目:
String[] dataArray = data.split(":");
map.put(JoystickEnum.valueOf(dataArray[0]), dataArray[1]);
假设Property与枚举值匹配,且Value不包含任何":"。
英文:
if data is a String of the format "Property:Value" and map an object of type Map<JoystickEnum, String> you can add an entry as follow
String[] dataArray = data.split(":");
map.put(JoystickEnum.valueOf(dataArray[0]), dataArray[1]);
assuming that Property match with an enum value and Value won't contain any ":"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论