[英]How do I store values inside my array?
我正在尝试创建一个程序,允许用户在输入数组的行和列,输入数组内的值以及输出数组之间进行选择。 一切正常,直到我尝试输出数组,它总是输出0。 如何正确打印值?
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');
}
您正在重新创建每个循环的数组,丢弃您保存的任何值。 你需要发表声明
int[][] array = new int[0][0];
在do {} while
循环之前。 然后,您可以创建一个用户在第一种case
指定的大小的数组:
...
column = sc.nextInt();
array = new int[row][column];
移动
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);
// 这里
int array[][] = new int [row] [column];
break;
移动= new int [row] [column];
在你读完数组的大小后。 例如。
int array = null;
switch (Character.toLowerCase(c))
<snip>
...
</snip>
array = new int [row] [column];
break;
case 'b':
for (int r=0; r < row; r++)
您现在不断用新的数组覆盖您的数组(填充0)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.