首页 > 解决方案 > 将字符映射转换为数组

问题描述

我正在尝试使用基本的tictactoe示例来学习java,但只是为了好玩,我想稍后设计一个ai。

我在将 char[] 展平为 Array 时遇到问题。我很困惑有没有更好的方法来做到这一点?我是否需要创建另一种方法来具体将此 char[] 转换为数组?

错误:

The method mapToCharater(Charater.class::cast) is undefined for the type Stream<Object>

控制台输出

编辑:

Exception in thread "main" java.lang.ClassCastException: Cannot cast [C to java.lang.Character
    at java.base/java.lang.Class.cast(Class.java:3610)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:523)
    at aiPackage.game.Board.<init>(Board.java:17)
    at aiPackage.game.Tester.main(Tester.java:15)

    package aiPackage.game;

    import java.util.*;
    import java.util.stream.*;

    public class Board {
        //declaration of private members
        private int score;
        private Board previousB = null;
        private char[][] thisBoard;

        // ------------------------------------------------------;

        public Board (char [][] inBoard) {
            //what
            //char[] flats = flatten(inBoard).map
            Object[] flats = flatten(inBoard).map(Character.class::cast).toArray(); //mapToCharater(Charater.class::cast).toArray();

            int[] flat = flatten(inBoard).mapToInt(Integer.class::cast).toArray();
            int flatSize = flat.length;


            // ------------------------------------------------------;

            //check if square
            if (Math.sqrt(flatSize)==3) {
                if(inBoard.length == 3) {
                    thisBoard = inBoard;
                }
                else {
                    System.out.println("The array isnt a square.");
                }
            }
            else {
                System.out.println("It doesnt match the dimensions of a tictactoe board.");
            }

            //we'll assume its not gonna break from the input atm
            setThisBoard(inBoard);
        }

        //https://stackoverflow.com/questions/31851548/flatten-nested-arrays-in-java
        private static Stream<Object> flatten(Object[] array) {
            return Arrays.stream(array)
                    .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
        }

        public Board getPreviousB() {
            return previousB;
        }

        public void setPreviousB(Board previousB) {
            this.previousB = previousB;
        }

        public int getScore() {
            return score;
        }

        public void setScore(int score) {
            this.score = score;
        }

        public char[][] getThisBoard() {
            return thisBoard;
        }

        public void setThisBoard(char[][] thisBoard) {
            this.thisBoard = thisBoard;
        }

        //if there are even elements on the board, its x's turn
        public ArrayList<Board> getChildren(){

            return null;
        }

        public void checkIfEnded() {
            for (int i = 0; i < 3; i++) {
                //check row wins
                if (thisBoard[i][0] != '-' &&
                        thisBoard[i][0] == thisBoard[i][1] &&
                        thisBoard[i][1] == thisBoard[i][2]) {

                    //updates score based on winner
                    if (thisBoard[0][2] == 'x') {
                        updateScore(1);
                    }
                    else {
                        updateScore(-1);
                    }

                    return;
                }

                //check column wins
                if (thisBoard[i][0] != '-' &&
                        thisBoard[0][i] == thisBoard[1][i] &&
                        thisBoard[1][i] == thisBoard[2][i]) {

                    //updates score based on winner
                    if (thisBoard[0][2] == 'x') {
                        updateScore(1);
                    }
                    else {
                        updateScore(-1);
                    }

                    return;
                }


            }

            //check diagnals
            if (thisBoard[0][0] != '-' &&
                    thisBoard[0][0] == thisBoard[1][1] &&
                    thisBoard[1][1] == thisBoard[2][2]) {

                //updates score based on winner
                if (thisBoard[0][2] == 'x') {
                    updateScore(1);
                }
                else {
                    updateScore(-1);
                }

                return;
            }
            if (thisBoard[0][2] != '-' &&
                    thisBoard[0][2] == thisBoard[1][1] &&
                    thisBoard[1][1] == thisBoard[2][0]) {

                //updates score based on winner
                if (thisBoard[0][2] == 'x') {
                    updateScore(1);
                }
                else {
                    updateScore(-1);
                }

                return;
            }
        }

        //outputs the board's contents as a string
        public String toString() {
            String result = "";

            //gets the previous board's info to output first
            result = "" + previousB;

            //gets this boards info to output
            for(int i = 0; i < 3; i++) {
                for(int j = 0; j < 3; j++) {
                    result += thisBoard[i][j] + " ";
                }

                //adds newline char at end of row
                result += "\n";
            }
            //adds an extra newline char at end of board
            result += "\n";

            return result;
        }

        private void updateScore(int win) {
            if (win > 0) {
                score = 1;
            } else if(win == 0){
                score = 0;
            }else {
                score = -1;
            }
        }
    }
package aiPackage.game;

import java.util.*;

public class Tester {
    private static Board start;
    private static Board finish;

    public static void main(String[] args) {
        char temp [][] = {
            {'o','-','x'},
            {'-','-','-'},
            {'-','-','-'}};

        start = new Board(temp);
        finish = minMax(start.getChildren());
        System.out.println();

    }

    public static Board minMax(ArrayList<Board> resultList) {


        return null;
    }



}

标签: javatic-tac-toe

解决方案


它失败的原因是因为Arrays.stream()不接受char[]以下应该工作。

Arrays.stream(inBoard)
      .flatMap(x -> (Stream<Character>)new String(x).chars().mapToObj(i->(char)i))
      .collect(Collectors.toList())

查看 想要在 java中从 char 数组创建字符流,以及 为什么 String.chars() 在 Java 8 中是整数流? 为了更好地理解。


推荐阅读