题目大意是:W和L两人来玩游戏,分别以11分和21分记为一局,输入为'W'代表W得1分,同理'L'为L得一分。
输入条件:标准输入,可多行输入,以'E'作为输入结束标识。
输出:分别打印计分为11和21的游戏结果,以空行隔开。
暂不考虑输入校验,简单实现如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int w11Result = 0;
int w21Result = 0;
int l11Result = 0;
int l21Result = 0;
List<String> result11 = new ArrayList<String>();
List<String> result21 = new ArrayList<String>();
int count = 0;
while (sc.hasNext()) {
String input = sc.nextLine();
char[] inputArray = input.toCharArray();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] == 'W') {
w11Result++;
w21Result++;
count++;
}
if (inputArray[i] == 'L') {
l11Result++;
l21Result++;
count++;
}
if (count >= 11 && count % 11 == 0) {
result11.add(w11Result + ":" + l11Result);
w11Result = 0;
l11Result = 0;
}
if (count >= 21 && count % 21 == 0) {
result21.add(w21Result + ":" + l21Result);
w21Result = 0;
l21Result = 0;
}
}
if (inputArray[inputArray.length - 1] == 'E') {
result11.add(w11Result + ":" + l11Result);
result21.add(w21Result + ":" + l21Result);
System.out.println("Game over, results of 11 points:");
result11.forEach(System.out::println);
System.out.println();
System.out.println("Game over, results of 21 points:");
result21.forEach(System.out::println);
break;
}
}
}
}
测试结果:
//单行输入
E
Game over, results of 11:
0:0
Game over, results of 21:
0:0
//单行输入
WLWWWLLLLLLWLLWLWLWE
Game over, results of 11:
4:7
4:4
Game over, results of 21:
8:11
//多行输入
WWWLLL
WLWLWLWLLWLLWLLWLWL
WLWLLWLE
Game over, results of 11:
6:5
4:7
4:6
Game over, results of 21:
9:12
5:6
//多行输入
WLWLWL
WLWLWLLLLLLL
WLWLLLLLLLLLLLLLWLWLWL
WLLLLLLWWWWWWWWWWWWWWWWWW
E
Game over, results of 11:
6:5
2:9
0:11
4:7
8:3
10:0
Game over, results of 21:
8:13
4:17
16:5
2:0