Thread.sleep方法更改所需的结果

时间:2019-04-30 01:26:23

标签: java

我在这里有一个项目的代码。在实现sleep方法之前,它可以按预期工作。然后,当我增加睡眠时,它并没有显示出想要的结果。

我是Java新手,对使用sleep方法没有真正的经验。

import java.util.Scanner;

public class Driver2 {

    public static void main(String[] args) 
    {    
        //initialize variables for user input on sleep and generations.
        long t;
        double gen;
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the length of time between generations: ");
        t = input.nextLong();

        System.out.print("Enter the number of generations: ");
        gen = input.nextDouble();

        // Create a new GamOfLife object
        GameOfLife g = new GameOfLife();
        char[][] tempBoard = new char[g.getRows()][g.getColumns()];
        // Inialize tempBoard to be all 0 
        for(int d = 0; d < g.getRows(); d++)
        {
            for(int j = 0; j < g.getColumns(); j++)
                tempBoard[d][j] = '0';          
        }

        // Set board in GameOfLife instance
        g.setGameBoard(tempBoard);
        // Set initial pattern 
        g.putGlider();
        // Print the gameboard with the initial patter
        g.printGameBoard();

        // 100 Generations
        for (int i = 0; i < gen; i++)
        {
            /* Create a temporary board that represents the next generation of cells
               Cannot change the gameboard directly because it will change the 
               number of surrounding neighbors of the cell next to it. */ 
            for(int d = 0; d < g.getRows(); d++)
            {
                for(int j = 0; j < g.getColumns(); j++)
                    tempBoard[d][j] = '0';          
            }

            for (int r = 0; r < g.getRows();r++)
            {
                for (int c = 0; c < g.getColumns(); c++)
                {
                    // Cell is dead and has 3 neighbors (alive in next generation)
                    if (g.deadOrAlive(r, c) == false && g.getNeighbors(r, c) == 3)
                        tempBoard[r][c] = '1';
                    // Cell is alive and has 2 or 3 neighbors (remains alive for next generation)
                    else if (g.deadOrAlive(r, c) && ((g.getNeighbors(r, c) == 3 || g.getNeighbors(r, c) == 2)))
                        tempBoard[r][c] = '1';
                    // all other cases the cell dies
                    else
                        tempBoard[r][c] = '0';
                }
            }
            System.out.println("Generation " + (i + 1));
            // Set the new gameboard as the tempboard all at once after checking the conditions for each dimenison
            try {
                Thread.sleep(t);
            }
            catch (InterruptedException ex)
            {

            g.setGameBoard(tempBoard);
            }
            g.printGameBoard();

        }
    }
}

应该发生的是,滑翔机(或形状,如果愿意的话)沿着我设置的游戏板移动。它运行完美,但是我需要减慢每一代之间的执行速度。然后,当我实现sleep方法时,滑翔机根本不会动。

0 个答案:

没有答案