2015-06-29 230 views
2

我想创建一个程序,允许用户在输入数组的行和列,输入数组内的值和输出数组之间进行选择。它一切正常,直到我尝试输出数组,它总是输出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'); 
} 
+0

你检查过矩阵的大小吗?你不是一次又一次地替换同一个单元吗? – Bharadwaj

+0

什么是菜单(sc)? –

回答

3

移动

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; 
5

你现在重新创建你的阵列中的每个循环,放弃你的任何值保存。您需要将

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

之前的do {} while循环。然后,您可以创建用户指定在第一case大小的数组:

... 
column = sc.nextInt(); 
array = new int[row][column]; 
+1

另外'INT [] []数组= ..'读取比'int数组[] []' –

+1

虽然这是好事,外部移动阵列的声明要被用户执行后(前)循环中,我们仍然需要其初始化更好将提供适当的大小,所以我们需要像'array = new int [row] [column];'在case'a'结尾的代码。 – Pshemo

1

移动= 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填充)。

相关问题