如何使用格式化字符串 “Property:Value” 创建属性地图。

huangapple go评论73阅读模式
英文:

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(&quot;:&quot;);
map.put(JoystickEnum.valueOf(dataArray[0]), dataArray[1]);

assuming that Property match with an enum value and Value won't contain any ":"

huangapple
  • 本文由 发表于 2020年10月16日 02:45:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64377906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定