一道基本的Java笔试题,老王和老刘玩游戏

题目大意是: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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值