解析并查找具有可变数量的字段java的字符串

时间:2021-04-13 23:13:51

I have to read a file and store the values and then later do a lookup.

我必须读取文件并存储值,然后再进行查找。

For e.g., the file will look as follows:

例如,该文件将如下所示:

Gryffindor = 5
Gryffindor.Name.Harry = 10
Gryffindor.Name.Harry.Cloak.Black = 15
and so on...

I need to store these (I was thinking of a map). Later, I need to process every character and lookup this map to assign them points. Suppose I encounter Harry, I know that he's from Gryffindor and he's wearing a blue cloak. I will have to lookup this map (or whatever object I use) as

我需要存储这些(我正在考虑一张地图)。稍后,我需要处理每个字符并查找此映射以为它们分配点。假设我遇到哈利,我知道他来自格兰芬多,而且他穿着蓝色斗篷。我将不得不查找此地图(或我使用的任何对象)

Gryffindor.Name.Harry.Cloak.Blue

which should return me nothing. I then need to fall back to just the name and lookup

哪个应该归还我什么。然后我需要回到名称和查找

Gryffindor.Name.Harry

that should return me a 10.

应该给我一个10。

Similarly, if I lookup for Ron, (suppose he's wearing black),

同样,如果我查找Ron,(假设他穿着黑色),

Gryffindor.Name.Ron.Cloak.Black

should return nothing, fall back to

应该什么也不回来,倒退

Gryffindor.Name.Ron

again nothing, fall back to

再没什么,回头

Gryffindor

which should return 5.

哪个应该返回5。

What will be an elegant way to store and read this data? I was thinking of using a map for storing the key value pairs and then a switch case to read them back. How would you do it?

存储和读取这些数据的优雅方式是什么?我正在考虑使用地图存储键值对,然后使用开关盒来读取它们。你会怎么做?

1 个解决方案

#1


0  

Java has a built-in Properties class that implements Map and can read and write the data format you describe (see that class's load() and store() methods).

Java有一个内置的Properties类,它实现了Map,可以读写你描述的数据格式(参见该类的load()和store()方法)。

There's nothing in there to implement your "fall back to a higher-level key" feature, so you'll need to write a method that looks in the Properties instance for data under the desired key, and keeps trying successively shorter versions of the same key if it finds nothing.

没有任何内容可以实现“回退到更高级别的密钥”功能,因此您需要编写一个方法,在Properties实例中查找所需密钥下的数据,并继续尝试相同的更短版本如果找不到任何关键。

#1


0  

Java has a built-in Properties class that implements Map and can read and write the data format you describe (see that class's load() and store() methods).

Java有一个内置的Properties类,它实现了Map,可以读写你描述的数据格式(参见该类的load()和store()方法)。

There's nothing in there to implement your "fall back to a higher-level key" feature, so you'll need to write a method that looks in the Properties instance for data under the desired key, and keeps trying successively shorter versions of the same key if it finds nothing.

没有任何内容可以实现“回退到更高级别的密钥”功能,因此您需要编写一个方法,在Properties实例中查找所需密钥下的数据,并继续尝试相同的更短版本如果找不到任何关键。