Search code examples
javamultidimensional-arrayuser-input

Inserting user input into a double dimensional array


My teacher wants me to write code that asks the users for the number of rows and columns they want then use that input to create a 2d array. But every time I try to put the variable into the rows and columns brackets I get this Error for line 17:

"The expression must be an array type but it resolved to a class"

package Theatre;

import java.util.Scanner;

public class BoxOffice {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in); 

        System.out.print("How many rows do you want in your Theatre");
        int r = input.nextInt(); input.nextLine();
        System.out.print("How many Columns do you want in your Theatre");
        int c = input.nextInt(); input.nextLine();
        System.out.printf("You want %d rows and %d columns in your Theatre", r, c);
        int [] [] seat = int [r] [c];  // <-- line 17

I expected to line 17 to create a 2d array with the rows the user wanted variable r in the row brackets and the columns in the columns bracket but I get an error.


Solution

  • Scanner input = new Scanner(System.in);

        System.out.print("How many rows do you want in your Theatre");
        int r = input.nextInt(); input.nextLine();
        System.out.print("How many Columns do you want in your Theatre");
        int c = input.nextInt(); input.nextLine();
        System.out.printf("You want %d rows and %d columns in your Theatre", r, c);
    
    
        int [] [] seat = new int [r] [c];
    

    You forgot to put the new Keyword on your array declaration.