1

I'm trying to write a program that takes input from the user, defining the number of rows and columns in an array, and then allows you to input elements one at a time. I don't know where to initialize my two arrays (a and b) because if I define the arrays inside my askUser method I can't figure out how to use it anywhere else, and if I define the arrays outside methods, I can't write to the array length. Any help is greatly appreciated.

public class Main{
  public void askUser(){
    System.out.print("How wide do you want the arrays to be: ");
    width = sc.nextInt();

    System.out.print("How tall do you want the arrays to be: ");
    height = sc.nextInt();
    for(int w = 0; w < height; w++){
      for(int h = 0; h<width; h++){
        length++;
      }
    }
    int[][] a = new int[height][width];
    int[][] b = new int[height][width];

    for(int i = 0; i < height; i++){
      for(int n = 0; n<width; n++){
        System.out.print("What do you want ["+i+", "+n+"] to be: ");
        a[i][n] = sc.nextInt();
        b[i][n] = sc.nextInt();

      }
    }

  }
  public static void main(String[] args) {
    Main obj = new Main();
    obj.askUser();

  }
}
Alex Rumer
  • 31
  • 6
  • Does this answer your question? [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – bad_coder Nov 20 '20 at 02:40

1 Answers1

0

Declare int[][] a and int[][] b as instance variables (as shown below) so that you can access them in the methods of this class.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    Scanner sc = new Scanner(System.in);
    int[][] a;
    int[][] b;

    public void askUser() {
        System.out.print("How wide do you want the arrays to be: ");
        int width = sc.nextInt();

        System.out.print("How tall do you want the arrays to be: ");
        int height = sc.nextInt();

        a = new int[height][width];
        b = new int[height][width];

        for (int i = 0; i < height; i++) {
            for (int n = 0; n < width; n++) {
                System.out.print("What do you want [" + i + ", " + n + "] to be: ");
                a[i][n] = sc.nextInt();
                b[i][n] = sc.nextInt();
            }
        }
    }

    public void display() {
        System.out.println(Arrays.deepToString(a));
        System.out.println(Arrays.deepToString(b));
    }

    public static void main(String[] args) {
        Main obj = new Main();
        obj.askUser();
        obj.display();
    }
}

A sample run:

How wide do you want the arrays to be: 2
How tall do you want the arrays to be: 2
What do you want [0, 0] to be: 1 2
What do you want [0, 1] to be: 3 4
What do you want [1, 0] to be: 5 6
What do you want [1, 1] to be: 7 8
[[1, 3], [5, 7]]
[[2, 4], [6, 8]]
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72