我在创建包含2个数组的方法时遇到了困难。我理解了如何创建方法和创建2d数组的概念,但我正在努力将两者结合起来。我必须创建一个从32到-31的网格(参见代码),但必须使用JOptionPane
的方法显示。主要是我在创建和调用方法时迷失了所有[],{}和()。谁可以通过讲述(或解释)如何创建和调用二维方法来帮助我?
非常感谢。
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");
}
}
}
答案 0 :(得分:1)
或多或少的整个代码都是正确的。
不是在控制台中打印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;
}
可以返回字符串
现在从所需位置调用此方法并在JOptionPane中显示String。
String a = something();
JOptionPane.showMessageDialog(null,a);
希望这能解决您的问题
答案 1 :(得分:0)
private int[][] myMethodName() {
return myDoubleIntArray;
}
答案 2 :(得分:0)
在下文中,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;
}
}