我正在开发我的新Java应用程序。它是二十一点游戏分析器。服务器将二十一点游戏结果发送给用户,我的应用程序对其进行解析,然后向用户显示游戏描述。游戏结果如下所示: #N145. 20(9♥️,6♠️,J♠️,Q♦️) - 19(8♦️,A♠️)
这里的 145 是游戏号码,20 是赌场的分数,19 是玩家的分数。并且此行应解析为游戏对象。这是游戏类:
//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方法。