Java 如何将输入设置为公共常量

Java 如何将输入设置为公共常量,java,Java,大家好,我有代码main和tictactoe类 这里是我的例子 主要阶级的。在这段代码中,我输入了字符串数字之类的内容 public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Scanner scanner = new Scanner(System.in);

大家好,我有代码main和tictactoe类

这里是我的例子 主要阶级的。在这段代码中,我输入了字符串数字之类的内容

public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                 Scanner scanner = new Scanner(System.in);
                 System.out.println("Enter number of ROW Column Do you want to use");
                 String input = scanner.next();
                 Integer Input = Integer.parseInt(input);
                new TTTGraphics2P(Input); // Let the constructor do the job
             }
          });
这是为我的Tictatcoe课程准备的。如果我运行这个代码,我只有3x3的tictactoe程序,所以我想用我的输入修改其中一个代码,这样我的tictactoe将是input x input

public class TTTGraphics2P extends JFrame {
   // Named-constants for the game board
   public static final int ROWS = 3;  // ROWS by COLS cells
   public static final int COLS = 3;
 
   // Named-constants of the various dimensions used for graphics drawing
   public static final int CELL_SIZE = 100; // cell width and height (square)
   public static final int CANVAS_WIDTH = CELL_SIZE * COLS;  // the drawing canvas
   public static final int CANVAS_HEIGHT = CELL_SIZE * ROWS;
   public static final int GRID_WIDTH = 8;                   // Grid-line's width
   public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2; // Grid-line's half-width
   // Symbols (cross/nought) are displayed inside a cell, with padding from border
   public static final int CELL_PADDING = CELL_SIZE / 6;
   public static final int SYMBOL_SIZE = CELL_SIZE - CELL_PADDING * 2; // width/height
   public static final int SYMBOL_STROKE_WIDTH = 8; // pen's stroke width
 
   // Use an enumeration (inner class) to represent the various states of the game
   public enum GameState {
      PLAYING, DRAW, CROSS_WON, NOUGHT_WON
   }
   private GameState currentState;  // the current game state
 
   // Use an enumeration (inner class) to represent the seeds and cell contents
   public enum Seed {
      EMPTY, CROSS, NOUGHT
   }
   private Seed currentPlayer;  // the current player
 
   private Seed[][] board   ; // Game board of ROWS-by-COLS cells
   private JPanel canvas; // Drawing canvas (JPanel) for the game board
   private JLabel statusBar;  // Status Bar
 
   /** Constructor to setup the game and the GUI components 
 * @param input */
   public TTTGraphics2P(Integer input) {
      canvas = new DrawCanvas();  // Construct a drawing canvas (a JPanel)
      canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
 
      // The canvas (JPanel) fires a MouseEvent upon mouse-click
      canvas.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {  // mouse-clicked handler
            int mouseX = e.getX();
            int mouseY = e.getY();
            // Get the row and column clicked
            int rowSelected = mouseY / CELL_SIZE;
            int colSelected = mouseX / CELL_SIZE;
 
            if (currentState == GameState.PLAYING) {
               if (rowSelected >= 0 && rowSelected < ROWS && colSelected >= 0
                     && colSelected < COLS && board[rowSelected][colSelected] == Seed.EMPTY) {
                  board[rowSelected][colSelected] = currentPlayer; // Make a move
                  updateGame(currentPlayer, rowSelected, colSelected); // update state
                  // Switch player
                  currentPlayer = (currentPlayer == Seed.CROSS) ? Seed.NOUGHT : Seed.CROSS;
               }
            } else {       // game over
               initGame(); // restart the game
            }
            // Refresh the drawing canvas
            repaint();  // Call-back paintComponent().
         }
      });
变成

公共静态final int ROWS=Input;//按COLS单元格排列的行 公共静态最终int COLS=输入

如何建造它


谢谢大家

,因为您已将变量声明为静态,它们将在加载类时初始化。由于它们是最终的,一旦设置,值就无法更改

为了达到您的要求,您可以修改TTTGraphics2P类,如下所示,以读取输入并在类加载时设置变量

public class TTTGraphics2P extends JFrame {
    // Named-constants for the game board
    public static final int ROWS = getInput();  // ROWS by COLS cells
    public static final int COLS = getInput();
    ...
    // Read standard input from the user
    public static int getInput() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of ROW Column Do you want to use");
        String input = scanner.next();
        return Integer.parseInt(input);
    }
    ...
}

正如您已将COLS变量声明为静态一样,它们将在加载类时初始化。由于它们是最终的,一旦设置,值就无法更改

为了达到您的要求,您可以修改TTTGraphics2P类,如下所示,以读取输入并在类加载时设置变量

public class TTTGraphics2P extends JFrame {
    // Named-constants for the game board
    public static final int ROWS = getInput();  // ROWS by COLS cells
    public static final int COLS = getInput();
    ...
    // Read standard input from the user
    public static int getInput() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number of ROW Column Do you want to use");
        String input = scanner.next();
        return Integer.parseInt(input);
    }
    ...
}

只需使用构造函数设置

public void run() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Total rows: ");
    int rows = scanner.nextInt();
    System.out.print("Total columns: ");
    int cols = scanner.nextInt();
    new TTTGraphics2P(rows, cols);
}

public class TTTGraphics2P extends JFrame {
    private final int rows;
    private final int cols;
    
    public TTTGraphics2P(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
    }
}

只需使用构造函数设置

public void run() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Total rows: ");
    int rows = scanner.nextInt();
    System.out.print("Total columns: ");
    int cols = scanner.nextInt();
    new TTTGraphics2P(rows, cols);
}

public class TTTGraphics2P extends JFrame {
    private final int rows;
    private final int cols;
    
    public TTTGraphics2P(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
    }
}

若将相同的值赋给最终变量,则无法更改它。它应该是非静态的。如果我们静态设置一个最终变量,我们就不能在构造函数中赋值。不要忘记声明没有值的最终变量。 声明没有值的最终变量

public final int ROWS;
 public final int COLS;
请参阅此示例程序以找到问题的解决方案

public class Solution {

    public final int ROWS;
    public final int COLS;

    public Solution(int input) {
        ROWS=input;
        COLS=input;
        System.out.println(ROWS);
    }

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int input=scanner.nextInt();
        Solution s=new Solution(input);
    }
} 

若将相同的值赋给最终变量,则无法更改它。它应该是非静态的。如果我们静态设置一个最终变量,我们就不能在构造函数中赋值。不要忘记声明没有值的最终变量。 声明没有值的最终变量

public final int ROWS;
 public final int COLS;
请参阅此示例程序以找到问题的解决方案

public class Solution {

    public final int ROWS;
    public final int COLS;

    public Solution(int input) {
        ROWS=input;
        COLS=input;
        System.out.println(ROWS);
    }

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int input=scanner.nextInt();
        Solution s=new Solution(input);
    }
} 

这是可行的,但却是一个糟糕的想法。在类初始化期间启动用户交互很容易导致问题,并且很难控制。更好的方法是不要使它们成为
静态final
,而是使它们成为实例变量。@JoachimSauer Yes 100%同意。这是一个理想的方法。这个方法可行,但却是一个糟糕的想法。在类初始化期间启动用户交互很容易导致问题,并且很难控制。更好的方法是不要使它们成为
静态final
,而是使它们成为实例变量。@JoachimSauer Yes 100%同意。这将是理想的方法。像这样的
静态final
基本上是一个编译时常量。首先,您必须使其成为非最终的,以便能够分配给它。然后,最好将其设置为非静态,因为静态非最终字段是要避免的全局状态。这样的
static final
基本上是一个编译时常量。首先,您必须使其成为非最终的,以便能够分配给它。然后,最好使其非静态,因为静态非最终字段是全局状态,需要避免。