从一个使用switch的方法中获取二维数组

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

嗨,我想从一个使用switch语句的方法中得到2d数组。我想得到num1或num2,所以其他方法可以使用这些数字。这可能吗,怎么做?这是我的代码。

public int[][] gameNumbers(){

    int rand = (int)(Math.random() * 2) + 1;

    switch(rand) {
    case 1:
        int [][] num1= {{4,3,5,2,6,9,7,8,1},{6,8,2,5,7,1,4,9,3},{1,9,7,8,3,4,5,6,2},{8,2,6,1,9,5,3,4,7},{3,7,4,6,8,2,9,1,5},{9,5,1,7,4,3,6,2,8},{5,1,9,3,2,6,8,7,4},{2,4,8,9,5,7,1,3,6},{7,6,3,4,1,8,2,5,9}};
        break;
    case 2:
        int [][] num2= {{1,7,4,3,5,2,9,6,8},{5,3,6,8,7,1,6,4,5,3},{2,9,8,7,1,6,4,5,3},{4,2,3,1,7,8,6,9,5},{8,5,7,2,6,9,3,4,1},{9,6,1,4,3,5,7,8,2},{3,8,2,6,4,7,5,1,9},{7,4,9,5,2,1,8,3,6},{6,1,5,9,8,3,2,7,4}};
        break;
    default:
        break;
    }

    return rand;
}
java arrays switch-statement return-value
1个回答
1
投票

你已经很接近了。这应该可以做到。

在switch语句之前声明结果变量,并将其赋值到switch中。

public int[][] gameNumbers(){

    // Declare this before the switch so it stays in scope.
    int[][] result;

    int rand = (int)(Math.random() * 2) + 1;
    switch(rand) {
    case 1:
        result = new int[][]{{4,3,5,2,6,9,7,8,1},{6,8,2,5,7,1,4,9,3},{1,9,7,8,3,4,5,6,2},{8,2,6,1,9,5,3,4,7},{3,7,4,6,8,2,9,1,5},{9,5,1,7,4,3,6,2,8},{5,1,9,3,2,6,8,7,4},{2,4,8,9,5,7,1,3,6},{7,6,3,4,1,8,2,5,9}};
        break;

    case 2:
        result = new int[][]{{1,7,4,3,5,2,9,6,8},{5,3,6,8,7,1,6,4,5,3},{2,9,8,7,1,6,4,5,3},{4,2,3,1,7,8,6,9,5},{8,5,7,2,6,9,3,4,1},{9,6,1,4,3,5,7,8,2},{3,8,2,6,4,7,5,1,9},{7,4,9,5,2,1,8,3,6},{6,1,5,9,8,3,2,7,4}};
        break;

    default:
        result = null;
        break;
    }
    return result;
}

2
投票

由于你想得到十个可能的9x9数组中的一个,你可以这样尝试。你把这十个数组放在另一个数组中,然后随机返回一个即可。

private static int[][][] arrays = new int[][][]{
        {{4, 3, 5, 2, 6, 9, 7, 8, 1}, {6, 8, 2, 5, 7, 1, 4, 9, 3}, {1, 9, 7, 8, 3, 4, 5, 6, 2}, {8, 2, 6, 1, 9, 5, 3, 4, 7}, {3, 7, 4, 6, 8, 2, 9, 1, 5}, {9, 5, 1, 7, 4, 3, 6, 2, 8}, {5, 1, 9, 3, 2, 6, 8, 7, 4}, {2, 4, 8, 9, 5, 7, 1, 3, 6}, {7, 6, 3, 4, 1, 8, 2, 5, 9}},
        {{1, 7, 4, 3, 5, 2, 9, 6, 8}, {5, 3, 6, 8, 7, 1, 6, 4, 5, 3}, {2, 9, 8, 7, 1, 6, 4, 5, 3}, {4, 2, 3, 1, 7, 8, 6, 9, 5}, {8, 5, 7, 2, 6, 9, 3, 4, 1}, {9, 6, 1, 4, 3, 5, 7, 8, 2}, {3, 8, 2, 6, 4, 7, 5, 1, 9}, {7, 4, 9, 5, 2, 1, 8, 3, 6}, {6, 1, 5, 9, 8, 3, 2, 7, 4}}
        // ... more 8 arrays
};

public int[][] gameNumbers() {
    int idx = (int) (Math.random() * 10);
    return arrays[idx];
}
© www.soinside.com 2019 - 2024. All rights reserved.