2016-08-25 70 views
0
for(i=0; i<=2; i++){ 
    if(i=0){ 
     System.Out.println("Input x: "); 
     int x=input.nextInt(); 
     if(x==1){ 
      char[] a={'A','B','C'}; 
     } 
     else if(x=2){ 
      char[] a={'D','E','F'}; 
     } 
     else{ 
      char[] a={'G','H','I'}; 
     } 
    } 

由於循環&由輸入x決定的值,a []的值將改變3次。我的問題是,如何將每個循環中[]的值存儲到另一個變量,並使用這些值創建另一個多維數組?????請任何人都幫我這個。提前致謝。如何創建一個動態改變簡單數組的多維數組?

+3

觀看了第一和第三if語句:您正在使用的分配算子,不平等! – Baderous

+0

你有什麼問題?據我看到你的代碼不會編譯。這是你想解決的問題嗎? – talex

回答

0

一些代碼來讓你去:

char[][] matrix = new char[2][4]; 
for (int i=0; i < 2; i++) { 
    // now create an array for the columns 
    matrix[i]= new char[4]; 
    // now you could do 
    for (int j=0; j < 4; j++) { 
    matrix[i][j] = ... 
    } 
    // or 
    char[] row = { '1', '2', '3', '4' }; 
    matrix[i] = row; 
} 

的想法是,你先說你有多少行和列有。 然後迭代第一個維度,並且可以在每次迭代期間設置第二個維度的值。

+0

我不認爲用這樣的數組初始值設定是合法的...... –

+0

@StephenC爲什麼不呢? – user1803551

+0

@StephenC你是對的,謝謝你的輸入! – GhostCat

1

很難確定你在找什麼,但這可能會給你一些想法。至少,語法應該是正確的:

char[][] array = new char[3][]; 
for (int i = 0; i < array.length; i++) { 
    System.out.println("Input x: "); 
    int x = input.nextInt(); 
    if (x == 1) { 
     array[i] = new char[] {'A', 'B', 'C'}; 
    } else if (x == 2) { 
     array[i] = new char[] {'D', 'E', 'F'}; 
    } else { 
     array[i] = new char[] {'G', 'H', 'I'}; 
    } 
} 

注意事項:

  1. 案例是顯著。它是System.out而不是System.Out
  2. 使用=進行賦值,使用==來測試原始類型的相等性。 (但通常不是其他類型!)
  3. 正確縮進和一致使用空白對於可讀性非常重要。嘗試遵守風格指南。
+0

你「注意事項」與案件有問題。多麼諷刺:) – talex

+0

固定.................... –

0

我寧願解決您的問題建立在一個相當不提示代碼的要求,但在這裏有雲:

final int total=2; 
char[][] a=new char[total][]; 
for (int i=0;i<total;i++){ 
    System.Out.println("Input x: "); 
    int x=input.nextInt(); 
    switch(x){ 
     case 1: 
      a[i]=new char[]{'A','B','C'}; 
     break; 
     //Other cases... 
    } 
}