Java 将方法更改为类

Java 将方法更改为类,java,Java,我刚开始学习如何用java编写代码。我想把代码分成几个类,这样每个方法都是一个类。下面的代码从解决方案生成一个数独游戏。谢谢你的帮助 通过蛮力生成数独游戏 import java.util.Random; public class SudokuPuzzle { public int[][] puzzle = new int[9][9]; // Generated puzzle. public int[][] solved_puzzle = new int[9][9]

我刚开始学习如何用java编写代码。我想把代码分成几个类,这样每个方法都是一个类。下面的代码从解决方案生成一个数独游戏。谢谢你的帮助

通过蛮力生成数独游戏

import java.util.Random;
public class SudokuPuzzle
{
    public int[][] puzzle = new int[9][9];        // Generated puzzle.
    public int[][] solved_puzzle = new int[9][9]; // The solved puzzle.

private int[][] _tmp_grid = new int[9][9]; // For the solver
private Random rand = new Random();
private short solution_count; // Should be 1



/**
   * Constructor generates a new puzzle, and its solution
   */
public SudokuPuzzle()
{
    generateSolvedPuzzle(0);
    generatePuzzle();
}

/**
 * Finds a solved puzzle through depth-first search
 */
private boolean generateSolvedPuzzle(int cur_cell)
{
    if (cur_cell > 80)
        return true;

    int col = cur_cell % 9;
    int row = cur_cell / 9;

    // create a sequence of the integers {1,...,9} of random order
    int [] numbers = new int[9];
    for (int i=0; i < 9; i++)
        numbers[i] = 1+i;
    shuffle_array(numbers);

    for (int i=0; i < 9; i++)
    {
        int n = numbers[i]; // for the next number in the array
        // if number is acceptable by Sudoku rules
        if (!existsInColumn(solved_puzzle, n, col)
                && !existsInRow(solved_puzzle, n, row)
                && !existsInSubGrid(solved_puzzle, n, row, col))
        {
            // attempt to fill in the next cell with the current cell set to number
            solved_puzzle[row][col] = n;
            if (generateSolvedPuzzle(cur_cell + 1))
                return true;
            solved_puzzle[row][col] = 0; // didn't work, reset cell and try the next number in sequence
        }
    }
    return false; // unreachable (since search is exhaustive and a solved puzzle must exist)
}

/**
 * Solves the Sudoku puzzle through depth-first, exhaustive search, and store the number of
 * solutions in solution_count. Currently, we want to use this only to detect if two solutions
 * exist. Hence, we stop the search as soon as two solutions have been found.
 *
 *
 */
private boolean _solvePuzzle(int cur_cell)
{
    if (cur_cell > 80)
    {
        solution_count++;
        if (solution_count > 1) // two solutions detected. notify caller to abort search
            return true;
        return false;
    }

    int col = cur_cell % 9;
    int row = cur_cell / 9;

    if (_tmp_grid[row][col] == 0) // if cell is unfilled
    {
        for (int n=1; n <= 9; n++) // for each number
        {
            // if number is acceptable by Sudoku rules
            if (!existsInColumn(_tmp_grid, n, col)
                    && !existsInRow(_tmp_grid, n, row)
                    && !existsInSubGrid(_tmp_grid, n, row, col))
            {
                // attempt to fill in the next cell with the current cell set to number
                _tmp_grid[row][col] = n;
                if (_solvePuzzle(cur_cell + 1)) // notified of two solutions being detected
                    return true; // notify caller to abort search
                _tmp_grid[row][col] = 0; // try with other numbers
            }
        }
    }
    else
        if (_solvePuzzle(cur_cell + 1)) // notified of two solutions being detected
            return true; // notify caller to abort search

    return false;
}

private void shuffle_array(int array[])
{
    // swap the first size elements with other elements from the whole array
    for (int i = 0; i < array.length; i++)
    {
        // find an index j (i<j<=array_length) to swap with the element i
        int j = i + rand.nextInt(array.length - i);
        int t = array[j];
        array[j] = array[i];
        array[i] = t;
    }
}

/**
 * Returns whether a given number exists in a given column.
 *
 * @param col    column to check.
 * @param number number to check.
 * @return       true iff number exists in row.
 */
private boolean existsInColumn(int[][] puzzle, int number, int col)
{
    for (int row = 0; row < 9; row++)
        if (puzzle[row][col] == number)
            return true;
    return false;
}

/**
 * Returns whether a given number exists in a given row.
 *
 * @param row    row to check.
 * @param number number to check.
 * @return       true iff number exists in row.
 */
private boolean existsInRow(int[][] puzzle, int number, int row)
{
    for (int col = 0; col < 9; col++)
        if (puzzle[row][col] == number)
            return true;
    return false;
}

/**
 * Returns whether if the 3x3 sub-grid which includes (row, col) contains a
 * cell with the given number.
 *
 * @param row    a row in the sub-grid.
 * @param col    a col in the sub-grid.
 * @param number number to check.
 * @return       true iff sub-grid contains number.
 */
private boolean existsInSubGrid(int[][] puzzle, int number, int row, int col)
{
    int sub_grid_start_row = (row / 3)*3;
    int sub_grid_start_col = (col / 3)*3;
    for (int _row = sub_grid_start_row; _row < sub_grid_start_row + 3; _row++)
        for (int _col = sub_grid_start_col; _col < sub_grid_start_col + 3; _col++)
            if (puzzle[_row][_col] == number)
                return true;
    return false;
}

/**
 * Generates a Sudoku puzzle from a solved puzzle by setting up to 64 cells to 0.
 * (We cannot set more than 64 cells to 0. 
 */
private void generatePuzzle()
{
    // copy solved_puzzle to puzzle
    for (int row = 0; row < 9; row++)
        for (int col = 0; col < 9; col++)
            puzzle[row][col] = solved_puzzle[row][col];

    // create a sequence of the integers {0,...,80} of random order
    int [] cell_sequence = new int[81];
    for (int i=0; i < 81; i++)
        cell_sequence[i] = i;
    shuffle_array(cell_sequence);

    // attempt to set each cell in the sequence to 0
    int count_set_to_zero = 0;
    for (int i=0; i < 81 && count_set_to_zero < 64; i++)
    {
        int cur_cell = cell_sequence[i];
        int col = cur_cell % 9;
        int row = cur_cell / 9;
        int sav = puzzle[row][col];
        puzzle[row][col] = 0;
        solution_count = 0;

        // copy puzzle to _tmp_grid for the solver to work on
        for (int r = 0; r < 9; r++)
            for (int c = 0; c < 9; c++)
                _tmp_grid[r][c] = puzzle[r][c];

        if (_solvePuzzle(0)) // Puzzle allows more than 1 solution
            puzzle[row][col] = sav; // Revert to original puzzle
        else
            count_set_to_zero++;
    }
}

public void showSolution()
{
    for (int row = 0; row < 9; row++)
    {
        System.out.print("  ");
        for (int col = 0; col < 9; col++)
            System.out.print(" " + solved_puzzle[row][col]);
        System.out.println();
    }
}

public void show()
{
    for (int row = 0; row < 9; row++)
    {
        System.out.print("  ");
        for (int col = 0; col < 9; col++)
            System.out.print(" " + puzzle[row][col]);
        System.out.println();
    }
}

public static void main(String[] args)
{
    SudokuPuzzle sudoku_puzzle = new SudokuPuzzle();
    System.out.println("Puzzle:");
    sudoku_puzzle.show();
    System.out.println();
    System.out.println("Solution:");
    sudoku_puzzle.showSolution();
}
import java.util.Random;
公共类数独游戏
{
public int[][]拼图=新的int[9][9];//生成的拼图。
public int[]solved_puzzle=new int[9][9];//已解决的难题。
私有int[][]\u tmp\u grid=new int[9][9];//用于解算器
private Random rand=new Random();
私有短解决方案\u count;//应为1
/**
*构造函数生成一个新的谜题及其解决方案
*/
公共数独字谜()
{
产生溶解模糊(0);
generatePuzzle();
}
/**
*通过深度优先搜索查找已解决的难题
*/
专用布尔生成器olvedpuzzle(int cur_单元)
{
如果(电流单元>80)
返回true;
int col=当前单元格%9;
int行=当前单元格/9;
//创建随机顺序的整数{1,…,9}序列
整数[]个数=新整数[9];
对于(int i=0;i<9;i++)
数字[i]=1+i;
洗牌_数组(数字);
对于(int i=0;i<9;i++)
{
int n=numbers[i];//用于数组中的下一个数字
//如果数独游戏规则可以接受这个数字
如果(!existsInColumn)(已解决的谜题,n,col)
&&!existsInRow(已解决的难题,第n行)
&&!existsInSubGrid(已解决的_拼图,n,行,列))
{
//尝试用设置为数字的当前单元格填充下一个单元格
已解决的_拼图[行][col]=n;
if(生成溶解模糊(电流单元+1))
返回true;
已解决_拼图[row][col]=0;//不起作用,请重置单元格并按顺序尝试下一个数字
}
}
return false;//不可访问(因为搜索是穷举的,必须存在已解决的谜题)
}
/**
*通过深度优先、穷举搜索解决数独难题,并存储
*解决方案_中的解决方案计数。目前,我们只想使用此值来检测两个解决方案
*因此,一旦找到两种解决方案,我们就停止搜索。
*
*
*/
私有布尔解算(整数当前单元格)
{
如果(电流单元>80)
{
解决方案_count++;
if(solution_count>1)//检测到两个解决方案。通知调用方中止搜索
返回true;
返回false;
}
int col=当前单元格%9;
int行=当前单元格/9;
if(_tmp_grid[row][col]==0)//如果单元格未填充
{

对于(int n=1;n您可以创建一个包含执行命令的类,该命令执行命令应该执行的操作,但是您不能直接将方法转换为类。希望这有帮助:)

既然你的问题没有直接的答案,我就发表一点言论,希望能让你开窍。你所要求的内容比“我想把它从一个方法改成一个类”要多得多,主要是因为它没有那么简单

设计一个类需要很好的计划和理解。我假设你上面粘贴的代码没有经过真正的检查就可以正常工作,希望能从中得出一些例子

正如其他人已经指出的,你不能将一个方法转换成一个类,因为类包含方法。但是看看你的代码,你似乎在问“我如何将这个单一的类转换成多个”。这本质上是一个设计问题

一个
,在一个非常简单的层次上,通常代表一种真实世界的对象。一个类的实例是一个
对象
,你可以指向、引用、对其进行操作、创建、销毁或以其他方式。在这种情况下,一个类可能是一个
游戏
,或者更具体地说是一个
谜题
。谜题/g艾姆斯有规则,他们有球员,他们有分数,他们有时间限制,还有任何你能代表比赛的东西。这些东西中的每一个都是你可以创建的潜在类/对象

在您的代码中,您使用多维数组来表示游戏板。也许您希望将此对象转换为类?这有什么好处?它用于将您将在板上执行的操作与代码的其余部分直接分离

例如,您有方法
existsInColumn
existsInRow
existsInSubGrid
。这些方法直接在游戏网格上操作,应该与游戏执行逻辑的实际实现分离。将这些方法分离为类有助于简化代码以改进其维护可维护性、可读性、可扩展性和其他一系列能力。没有什么可以说你写的代码功能不一样,但是请任何程序员拿起你的代码,看看他们可以改变/改进什么,他们会拒绝说“我不会经历所有这些!”

回到正题…一旦你有了属于
SudokuPuzzle
GameGrid类或类似类,你就可以开始在拼图中创建方法,使用网格中的逻辑来解决问题。游戏的一部分将涉及以一种或另一种形式获取用户输入并将其传递到网格。可能是
Grid.insertNumber(int x,int y,int Number)
调用将是您从拼图中所需要的全部。然后,该方法可以调用上面的exists函数来确定它们的猜测是否正确

现在,显然还有很多话要说。你需要先坐下来决定如何设计你的游戏。会有
Player
对象吗?
Score
?这是一个使用
System.out.print()的命令行游戏吗
调用以使用Swing之类的库构建网格或图形化网格?一旦做出这些决定,您可以放下一些代码,然后返回需要解决的更具体的问题