我在创建包含2数组的方法时遇到了困难。我理解如何创建方法和创建二维数组的概念,但我正在努力将两者结合起来。我必须创建一个从32到-31的网格(见代码),但必须使用使用JOptionPane
的方法显示。主要是在创建和调用方法时,我迷失了所有的[],{}和()。谁能告诉我(或解释)如何创建和调用2d- array方法?
非常感谢。
import javax.swing.JOptionPane;//not beeing used yet, have to create JOptionPane
public class Inzend2 {
public static void main(String[] args) {
//over here I want to call a method for printing the blastTable in
//JOptionPane( for example printArray).
//Having difficulties on creating a method containing a
//two-dimensional array and how to call this method
//methode for creating blastTable, a grid of 8x8,
//start at 32, ends -31. How to make a method with a 2d-array?
// Am getting lost in all the [],{} and ()
int [][] blastTable = new int [8][8];
int lengteArray1 = blastTable.length;//is not beeing used,
// but created for my understanding on how to get the lenght of
//more dimensional array
int lengteArray2 = blastTable [0].length;
int beginpunt = 32;
for ( int x = 0; x < blastTable.length; x++) {
for ( int y = 0; y < lengteArray2; y++){
blastTable [x][y] = beginpunt;
beginpunt--;
System.out.print(blastTable[x][y]+ " ");
}
System.out.print("n");
}
}
}
你的代码或多或少是正确的。
不要在控制台中打印2D数组,而是将其存储在String变量中。然后您可以返回这个变量并使用它在JOptionPane中显示您的文本。
public String something() {
//over here I want to call a method for printing the blastTable in
//JOptionPane( for example printArray).
//Having difficulties on creating a method containing a
//two-dimensional array and how to call this method
//methode for creating blastTable, a grid of 8x8,
int [][] blastTable = new int [8][8];
int lengteArray2 = blastTable [0].length;
int beginpunt = 32;
String a="";
for ( int x = 0; x < blastTable.length; x++) {
for ( int y = 0; y < lengteArray2; y++){
blastTable [x][y] = beginpunt;
beginpunt--;
a+=beginpunt+" ";
}
a=a+"n";
}
System.out.println(a);
return a;
}
可以返回字符串a
现在从需要的地方调用这个方法,并在JOptionPane中显示字符串。
String a = something();
JOptionPane.showMessageDialog(null,a);
希望这能解决你的问题
private int[][] myMethodName() {
return myDoubleIntArray;
}
在下面,createArray()
可以返回一个int[][]
,但这里它只是将其设置为一个类变量:
public class TwoDArray {
private static int[][] board;
public static void main(String[] args) {
createBoard();
// add some pieces to some arbitrary locations
// REMEMBER, array indexes are zero based
addToBoard(0,0); // row 1, col 1
addToBoard(2,5); // row 3, col 6
addToBoard(3,7); // row 4, col 8
addToBoard(7,3); // row 8, col 4
// remove 1 piece
removeFromBoard(0,0);
for(int x = 0; x < board.length; x++) {
for(int y = 0; y < board.length; y++) {
System.out.println("position (row/col) :: " + (x + 1) + "/" + (y + 1) + " = " + board[x][y]);
}
}
}
private static void createBoard() {
if(board == null) {
board = new int[8][8];
}
}
/*
* value of 0 = empty square
* value of 1 = play piece in square
*/
private static void addToBoard(int rowPos, int colPos) {
board[rowPos][colPos] = 1;
}
private static void removeFromBoard(int rowPos, int colPos) {
board[rowPos][colPos] = 0;
}
}