Java 代码问题;我的代码结果与测试结果不匹配;试图找到错误

问题描述 投票:0回答:1

目的是总结所有可能的游戏 ID 号。 当没有数字超过其最大值时,游戏就可能进行。

  • 果岭最大为 13
  • 蓝调最大为 14
  • 红军上限为 12

每场比赛都有几次抽签。每次抽奖均以“;”分隔。 如果其中一场抽奖无法进行,则该游戏不会被视为可能,也不会添加到总和中。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ElfCubeGame {
    public static void main(String[] args) throws FileNotFoundException {
        File inputFile = new File("/Users/jakobschneider/Desktop/NeueFische/Projekte/Tag5_Nachmittag/src/main/resources/Test.txt");
        Scanner scanInput = new Scanner(inputFile);
        int maxRed = 12;
        int maxBlue = 14;
        int maxGreen = 13;
        int sumOfPossibleGames = 0;
        String line = "";

        while (scanInput.hasNextLine()) {
            line = scanInput.nextLine();

            String[] gameInfo = line.split(";");

            int gameId = Integer.parseInt(gameInfo[0].split(":")[0].replaceAll("\\D+", ""));

            boolean possibleGame = true;
            for (int i = 1; i < gameInfo.length; i++) {
                if (!isDrawPossible(gameInfo[i], maxRed, maxGreen, maxBlue)) {
                    possibleGame = false;
                    break;  // Break the loop once one draw is not possible
                }
            }
            if (possibleGame) {
                sumOfPossibleGames += gameId;
            }
        }

        System.out.println("Sum of Ids of possible games: " + sumOfPossibleGames);
    }

    private static boolean isDrawPossible(String draw, int maxRed, int maxGreen, int maxBlue) {
        // Count colors in the draw
        Pattern patternRed = Pattern.compile("(\\d+) red");
        Pattern patternBlue = Pattern.compile("(\\d+) blue");
        Pattern patternGreen = Pattern.compile("(\\d+) green");

        Matcher matcherRed = patternRed.matcher(draw);
        Matcher matcherBlue = patternBlue.matcher(draw);
        Matcher matcherGreen = patternGreen.matcher(draw);

        int valueRed = matcherRed.find() ? Integer.parseInt(matcherRed.group(1)) : 0;
        int valueBlue = matcherBlue.find() ? Integer.parseInt(matcherBlue.group(1)) : 0;
        int valueGreen = matcherGreen.find() ? Integer.parseInt(matcherGreen.group(1)) : 0;

        return valueRed <= maxRed && valueBlue <= maxBlue && valueGreen <= maxGreen;
    }
}

测试输入是:

Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green

结果应该是8。 我的代码结果是 11。

java java.util.scanner
1个回答
0
投票

此外,如果您的 IDE 支持,您还可以在调试会话期间在代码中添加一些条件断点,以提高效率。

© www.soinside.com 2019 - 2024. All rights reserved.