简体   繁体   中英

How to assign integer values into array and pass them on into another function?

I have made a multidimensional array(identifier[][]), that I assigned to a variable 'x', to identify the cells with integers 1-9, so I could work with them more comfortably. But, How can I assign the 'x' values into cell[] array, so I could pass it on into my main function and print it out in the for loop after ("Cell numbers are: ")? And If i need to change my printTable function, then how can I change it, so the return value would be an array ? (I am attempting to make a tic-tac-toe program)

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    printTable();
    System.out.print("Cell numbers are: ");
    for(int i = 0; i < 9; i++) {
        System.out.print("");
        if (i != 8) {
            System.out.print(", ");
        } else {
            System.out.print(".");
        }
    }
    input.close();
} // End of main.

public static void printTable() {
    int rows = 3;
    int columns = 3;
    int[][] identifier = new int[rows][columns];
    int x = 1;
    int[] cell = new int[9];


    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            identifier[i][j] = x;
            if (i == 0 && j == 0) {
                System.out.println("+---+---+---+");
            }

            System.out.print("| " + x + " ");
            cell[x];
            x++;


            if (j == columns - 1) {
                        System.out.print("|");
            }
        }
        System.out.println("");
        System.out.println("+---+---+---+");
    }
    System.out.println("Enter a number between (1-9): ");
} // End of printTable.

you table (array) must be a global variable. I suggest you to start creating a class Table, and start with the basis concepts of tic-tac-toe, like new table, clear table, show table, etc.

there are a lot of tutoriais around the internet, just pick one! good luck and let us know if you have questions.

[EDIT] this is looks like a good example. http://www.progressivejava.net/2012/11/How-to-make-a-Tic-Tac-Toe-game-in-Java.html

Not very good approach, but to fix your particular problem you need to

return result from printTable function:

public static void printTable() change to public static int[] printTable()

at the end of printTable function add return cell;

in the main funciton change printTable(); to int[] cell2 = printTable();

and change your "for loop":

for(int i = 0; i < 9; i++) { System.out.print(""); change to for(int i = 0; i < 9; i++) { System.out.print(cell2[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM