Home > OS >  Creating a Nth size grid using an array
Creating a Nth size grid using an array

Time:03-09

How would I create an Nth size array where all the values are the same such that it can form a grid. I'm pretty new to coding and just started with arrays.

This is my code so far. import java.util.Scanner;

public class Array_design {

public static void main(String[] args) {
    
    Scanner Row = new Scanner(System.in);
    System.out.println("Enter length of row");
        int row = Row.nextInt();

Scanner Col = new Scanner(System.in);
    System.out.println("Enter length of column");
        int col = Col.nextInt();
    // TODO Auto-generated method stub

    String[][] GameBoard = new String [row][col];
    
    GameBoard[][] = for (int J = 1; J <= row; J = J   1) {
        for (int I = 1; I <= col; I = I   1) {
             
            
            System.out.print("*");
            }
    
            // if user input equal declared variable
            System.out.println("");
                                    } 

}

}

}

CodePudding user response:

You don't need 2 scanners, one will do. Also, if you're only going to store a single character on each space, use a char instead of a String. You should move this to a GameBoard class and create an init() and output() method.

public static void main(String[] args) {
    
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter length of row");
    int row = scanner.nextInt();

    System.out.println("Enter length of column");
    int col = scanner.nextInt();

    char[][] gameBoard = new char [row][col];
 
    //Init the board
    for (int i = 0; i < gameBoard.length; i  ) {
        Arrays.fill(gameBoard[i], '*');
    }
    
    //output the board
    for (int i = 0; i < gameBoard.length; i  ) {
        System.out.println(Arrays.toString(gameBoard[i]));
    }
}

CodePudding user response:

What is going on with your code?

GameBoard[][] = for (int J = 1; J <= row; J = J 1)

Anyway, the way I would do this is probably

public class Array_design
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in); //initialize Scanner from System.in

        System.out.println("Enter length of row");
        int row = input.nextInt(); //input row
        System.out.println("Enter length of column");
        int col = input.nextInt(); //input column

        String[][] GameBoard = new String[row][col]; //initialize gameboard

        for (String[] arr : GameBoard) for (String s : arr) //enhanced-for loops
            s = "*"; //assign a value to every element in GameBoard; change this to whatever
    }
}
  • Related