面向对象的编程方式,代码量较多。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String input = sc.nextLine();
String[] poker = input.split("-");
if (poker.length != 2) {
System.out.println("ERROR");
return;
}
int result = compare(parse(poker[0]), parse(poker[1]));
System.out.println(result == 1 ? poker[0] : result == -1 ? poker[1] : "ERROR");
}
}
/**
* compare two poker cards
* @param poker1
* @param poker2
* @return 1 if first poker is larger; -1 if second poker is larger; 0 if not comparable
*/
private static int compare(Poker poker1, Poker poker2) {
PokerType p1 = poker1.type, p2 = poker2.type;
if (p1 == PokerType.JOKER) return 1;
if (p2 == PokerType.JOKER) return -1;
if (p1 == PokerType.BOOM) return 1;
if (p2 == PokerType.BOOM) return -1;
if (p1 != p2) return 0; // not comparable
return poker1.getValue() > poker2.getValue() ? 1 : -1;// type is the same
}
private static Poker parse(String rawCards) {
String[] cardArr = rawCards.split("\\s+");
switch (cardArr.length) {
case 1: return new Poker(getPokerValue(cardArr[0]), PokerType.SINGLE);
case 2:
if (cardArr[0].equals(cardArr[1])) {
return new Poker(getPokerValue(cardArr[0]), PokerType.PAIR);
}
else {
return new Poker(getPokerValue(cardArr[0]), PokerType.JOKER);
}
case 3: return new Poker(getPokerValue(cardArr[0]), PokerType.THREE);
case 4: return new Poker(getPokerValue(cardArr[0]), PokerType.BOOM);
case 5: return new Poker(getPokerValue(cardArr[0]), PokerType.STRAIGHT);
default:
// should not happen
throw new IllegalArgumentException("input is not valid " + rawCards);
}
}
private static int getPokerValue(String value) {
char firstChar = value.charAt(0);
if (value.length() > 1) {
switch (firstChar) {
case 'J': return 17; // Joker
case 'j': return 16; // joker
default: return 10; // 10
}
}
switch (firstChar) {
case 'J': return 11;
case 'Q': return 12;
case 'K': return 13;
case 'A': return 14;
case '2': return 15;
default:
return firstChar + (1 - '1');
}
}
public enum PokerType {
SINGLE, PAIR, THREE, BOOM, JOKER, STRAIGHT
}
public static class Poker {
/**
* SINGLE: value of the card
* PAIR: value of one of the card
* THREE: value of one of the card
* BOOM: value of one of the card
* JOKER: value of "joker"
* STRAIGHT: value of the first card
*/
private int value;
private PokerType type;
public Poker(int value, PokerType type) {
this.value = value;
this.type = type;
}
public int getValue() {
return value;
}
}
}