gpt4 book ai didi

java - 如何解析字符串二十一点游戏结果

转载 作者:行者123 更新时间:2023-12-02 09:47:49 25 4
gpt4 key购买 nike

我正在开发我的新 Java 应用程序。它是二十一点游戏分析仪。服务器将二十一点游戏结果发送给用户,我的应用程序解析它,然后向用户显示游戏描述。游戏结果如下所示:#N145。 20(9♥️,6♠️,J♠️,Q️️) - 19(8️️,A♠️)这里145是游戏号码,20是赌场的分数,19是玩家的分数。这一行应该被解析为 Game 对象。这是游戏类:

//import

public class Game {
private final int gameNumber;
private final boolean casinoWon;
private final Set<Card> gamerDeck;
private final Set<Card> casinoDeck;
private final int gamerScore;
private final int casinoScore;

public Game(int gameNumber, boolean casinoWon,
Set<Card> gamerDeck, Set<Card> casinoDeck,
int gamerScore, int casinoScore) {
this.gameNumber = gameNumber;
this.casinoWon = casinoWon;
this.gamerDeck = gamerDeck;
this.casinoDeck = casinoDeck;
this.gamerScore = gamerScore;
this.casinoScore = casinoScore;
}

//getters
}

我已经开始编写一个解析器,但我认为我做错了。这是其中的一堆代码:


//import

public class StringParser {
public Game parseStringToGame(String inputString) throws ParseException {
int gameNumber = -1;
boolean isCasinoWon = false;
int gamerScore = -1;
int casinoScore = -1;
String stringGamerDeck = "";
String stringCasinoDeck = "";

Iterator<Character> iterator = stringToCharacterList(inputString).iterator();
while(iterator.hasNext()) {
StringBuilder currentObject = new StringBuilder();
Character c = iterator.next();

if (c == '#')
c = iterator.next();
else
throw new ParseException();

if (c == 'N')
c = iterator.next();
else
throw new ParseException();

while(Character.isDigit(c)) {
currentObject.append(c);
c = iterator.next();
}
gameNumber = Integer.parseInt(currentObject.toString());
currentObject = new StringBuilder();
//c=='.'
if (c == '.')
c = iterator.next();
else
throw new ParseException();

//c==' '
if (c == ' ')
c = iterator.next();
else
throw new ParseException();

//to be continued

}
}

private List<Character> stringToCharacterList(String s) {
List<Character> characters = new LinkedList<>();
for (char c : s.toCharArray())
characters.add(c);
return characters;
}
}

如你所见,它看起来非常恶心。有没有更“高级”的方法来解析字符串?

最佳答案

如果游戏的输出始终是固定的,您可以使用正则表达式来完成此任务。

    Pattern p = Pattern.compile("^#N(\\d*).\\s+(\\d*)(.+)\\s+-\\s+(\\d*)(.+)");
Matcher m = p.matcher(s);
m.find();
int gameNumber = Integer.valueOf(m.group(1));
int gamerScore = Integer.valueOf(m.group(2));
int casinoScore = Integer.valueOf(m.group(4));
boolean casinoWon = casinoScore - gamerScore > 0;
Set<Card> gamerDeck = parseDeck(m.group(3));
Set<Card> casinoDeck = parseDeck(m.group(5));

您所需要的只是实现 parseDeck 方法。

关于java - 如何解析字符串二十一点游戏结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56527847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com