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');
}
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With