我正在开发新的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;
}
}
如您所见,它看起来非常令人作呕。还有解析字符串的“高级”方法吗?
答案 0 :(得分:1)
如果游戏的输出始终固定,则可以将regexp用于此任务。
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方法。