Create an array in one function and read it in another without return statements

I'm trying to create an array in one method (or function? Or an object? The side question is what is the difference between all these words?), And then use its length in another method (and I will use it in other places). My teacher told me that I do not need to return the array, because I only change the location, so the array is not destroyed or something else. I would declare this basically, but then I cannot size it after I get the dimensional inputs (I don’t think?).

Anyone after this?

public class Update { public static void main(String[] args) { System.out.println("This program will simulate the game of Life."); createMatrix(); // birthAndLive(); printMatrix(); } public static void createMatrix() { Scanner console = new Scanner(System.in); System.out.println("Please input the size of your board."); System.out.println("Rows:"); final int rows = console.nextInt(); System.out.println("Columns:"); final int columns = console.nextInt(); System.out.println("Please enter a seed:"); final long seed = console.nextLong(); boolean[][] board = new boolean[rows][columns]; Random seedBool = new Random(seed); } public static void printMatrix() { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j] == false) System.out.print(" - "); else System.out.print(" # "); } System.out.println(); } } 
+4
source share
1 answer

You can solve this problem by passing the board your print function. A.

 class Update { public static void main(String[] args) { System.out.println("This program will simulate the game of Life."); createMatrix(); // birthAndLive(); printMatrix(); } public static void createMatrix() { Scanner console = new Scanner(System.in); System.out.println("Please input the size of your board."); System.out.println("Rows:"); final int rows = console.nextInt(); System.out.println("Columns:"); final int columns = console.nextInt(); System.out.println("Please enter a seed:"); final long seed = console.nextLong(); boolean[][] board = new boolean[rows][columns]; Random seedBool = new Random(seed); printMatrix(board); } public static void printMatrix(boolean[][] board) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { if (board[i][j] == false) System.out.print(" - "); else System.out.print(" # "); } System.out.println(); } } } 

I don’t know exactly how much code your teacher allows you to change. If all functions must be called from main , you will either have to put the array creation code in the main function, or you will have to resort to return statements or class variables.

+3
source

Source: https://habr.com/ru/post/1395102/


All Articles