2

I'm trying to create a program that allows the user to select between inputting the rows and columns of an array, inputting the values inside the array, and outputting the array. It all works fine until I try outputting the array, it always outputs 0's. How do I print the values properly?

public static void main(String[] args) { Scanner sc = new Scanner(System.in); char ans='y'; int column=0, row=0; do{ char c = menu(sc); int array[][] = new int [row] [column]; switch (Character.toLowerCase(c)) { case 'a': System.out.print("Enter row size "); row=sc.nextInt(); System.out.print("Enter column size "); column=sc.nextInt(); System.out.print("Row and Column "+row+" "+column); break; case 'b': for(int r=0;r<row;r++) { for(int col=0;col<column;col++) { System.out.print("Enter value for row "+r+" column "+col+": "); array[r][col]=sc.nextInt(); } } break; case 'c': for(int r=0; r<array.length; r++) { for(int col=0; col<array[r].length; col++) { System.out.print(array[r][col] + " "); } System.out.println(); } break; } System.out.println(""); }while(ans=='y'); } 
2
  • Did u check the size of the matrix? Aren't you replacing the same cell again and again? Commented Jun 29, 2015 at 13:43
  • what is menu(sc) doing? Commented Jun 29, 2015 at 13:44

3 Answers 3

5

You are recreating your array each loop, discarding any values you have saved. You need to put the declaration

int[][] array = new int[0][0]; 

before the do {} while loop. Then you can create an array of the size that the user specifies in the first case:

... column = sc.nextInt(); array = new int[row][column]; 
Sign up to request clarification or add additional context in comments.

1 Comment

While it is good to move declaration of array outside (before) loop we still need its initialization to be executed after user will provide proper sizes, so we need code like array = new int [row] [column]; at the end of case a.
3

Move

 int array[][] = new int [row] [column]; 

line to below spot:

switch (Character.toLowerCase(c)) { case 'a': System.out.print("Enter row size "); row=sc.nextInt(); System.out.print("Enter column size "); column=sc.nextInt(); System.out.print("Row and Column "+row+" "+column); 

// HERE

 int array[][] = new int [row] [column]; break; 

Comments

1

Move the = new int [row] [column]; to after you've read in the array's sizes. Eg.

int array = null; switch (Character.toLowerCase(c)) <snip> ... </snip> array = new int [row] [column]; break; case 'b': for (int r=0; r < row; r++) 

You are now continously overwriting your array with a new one (filled with 0s).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.