2015-06-29 115 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填充)。

相關問題