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

huangapple go评论65阅读模式
英文:

how to set input as public constanta

问题

以下是你要翻译的内容:

hi all i have code main and tictactoe class

here my example
of main class. in this code i input something like string number

    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
            }
        });

and this is for my class of tictactoe program. if i run this code i only have 3x3 tictactoe program, so i want to modify one of code using my input so my tictactoe will be 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().
         }
      });

你的问题是如何将以下字段更改为输入的值:

public static final int ROWS = 3;  // ROWS by COLS cells
public static final int COLS = 3;

更改为:

public static final int ROWS = Input;  // ROWS by COLS cells
public static final int COLS = Input;

解答:

要将这些字段更改为输入的值,你需要在构造函数 TTTGraphics2P 中传递一个参数 input,然后使用这个参数来初始化 ROWSCOLS 字段。在构造函数内部,将参数 input 分配给这两个字段,像这样:

public TTTGraphics2P(Integer input) {
   // ... (之前的代码)

   // 在构造函数内部将输入的值赋给 ROWS 和 COLS 字段
   ROWS = input;
   COLS = input;

   // ... (继续后续的代码)
}

然后,确保你的 ROWSCOLS 字段不再被声明为 final,因为你将在构造函数中为它们赋值。

英文:

hi all i have code main and tictactoe class

here my example
of main class. in this code i input something like string number

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println(&quot;Enter number of ROW Column Do you want to use&quot;);
String input = scanner.next();
Integer Input = Integer.parseInt(input);
new TTTGraphics2P(Input); // Let the constructor do the job
}
});

and this is for my class of tictactoe program. if i run this code i only have 3x3 tictactoe program, so i want to modify one of code using my input so my tictactoe will be 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&#39;s width
public static final int GRID_WIDHT_HALF = GRID_WIDTH / 2; // Grid-line&#39;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&#39;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 &gt;= 0 &amp;&amp; rowSelected &lt; ROWS &amp;&amp; colSelected &gt;= 0
&amp;&amp; colSelected &lt; COLS &amp;&amp; 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().
}
});

my question is i want to change this field

public static final int ROWS = 3;  // ROWS by COLS cells
public static final int COLS = 3;

become

public static final int ROWS = Input; // ROWS by COLS cells
public static final int COLS = Input;

how to build it ?

thank you all

答案1

得分: 1

只需使用构造函数设置rowscols

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;
    }
}
英文:

Just use constructor to set rows and cols:

public void run() {
Scanner scanner = new Scanner(System.in);
System.out.print(&quot;Total rows: &quot;);
int rows = scanner.nextInt();
System.out.print(&quot;Total columns: &quot;);
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;
}
}

答案2

得分: 1

如果将相同的值分配给最终变量,您将无法更改它。而且它应该是非静态的。如果我们将最终变量设为静态,就无法在构造函数中为其分配值。不要忘记声明没有值的最终变量。
声明没有值的最终变量。

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);
    }
}
英文:

If you assign same value to final variable you can't change it. And it should be a non-static. If we static a final variable we can't assign a value in constructor. And don't forget to declare final variable without value.
Declare final variables without value.

public final int ROWS;
public final int COLS;

Refer this sample program to find a solution for your problem.

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);
}
} 

答案3

得分: 0

由于您已将ROWSCOLS变量声明为static,它们将在类加载时进行初始化。由于它们是final的,一旦设置了值就不能更改。

为了实现您的要求,您可以按照以下方式修改TTTGraphics2P类,以读取输入并在类加载时将其设置为变量。

public class TTTGraphics2P extends JFrame {
    // 游戏棋盘的命名常量
    public static final int ROWS = getInput();  // 行乘以列的单元格数
    public static final int COLS = getInput();
    ...
    // 从用户读取标准输入
    public static int getInput() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要使用的行列数:");
        String input = scanner.next();
        return Integer.parseInt(input);
    }
    ...
}
英文:

As you have declared the ROWS and COLS variables as static they will be initialized when class is loaded. Since they are final, once set the value cannot be changed.

To achieve your requirement you can modify the TTTGraphics2P class as below to read the input and set to the variables at class loading.

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(&quot;Enter number of ROW Column Do you want to use&quot;);
String input = scanner.next();
return Integer.parseInt(input);
}
...
}

huangapple
  • 本文由 发表于 2020年9月13日 15:33:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63868307.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定