2014-02-27 37 views
1

我在下面的代碼中的方法「update()」有問題。我試圖使用數組作爲數組「hyp」的元素,因爲單個數組並不都具有相同的大小。 現在在更新函數中,我想比較存儲在各個數組的位置0的元素,例如天空[0],在hyp的第j個位置與trainingexample數組中的相應元素。 我的問題是,我只能訪問hyp數組中第j個位置的每個數組的地址。我嘗試將第j個位置的數組,即hyp [j]賦值給一個Object []類型的變量,但這不起作用。我應該只使用多維數組,即使其中會有空元素,還是比我想要做的更好的解決方案?使用數組作爲數組的元素

public class FindS { 
static Object[] sky = {"Sunny", "Cloudy", "?", "0", 0}; 
static Object[] airtemp = {"Warm", "Cold", "?", "0", 0}; 
static Object[] humidity = {"normal", "high", "?", "0", 0}; 
static Object[] wind = {"strong", "weak","?", "0",0}; 
static Object[] water = {"warm", "cold","?", "0", 0}; 
static Object[] forecast = {"same", "change","?", "0", 0}; 

static Object[] hyp = {sky,airtemp,humidity,wind, water, forecast}; 


public static String[] trainingexample = new String[7]; 


public static int findindex(Object[] a, String s){ 
    int index = 0; 
    while (index != a.length - 1){ 
     if (a[index] == s) 
      return index; 
     index++; 
    } 
    return -1; 

} 

public static void exchange(Object[] a, String s){ 
    int exchindex = findindex(a, s); 
    try{ 
     Object temp = a[exchindex]; 
     a[exchindex] = a[0]; 
     a[0] = temp; 
    } catch (ArrayIndexOutOfBoundsException e) 
    { 
     System.out.println(s + "not found"); 
    } 
} 

public void update(){ 
    if (trainingexample[6] == "0"); 
    else{ 
     int j = 0; 
     while (j != hyp.length){ 
      Object[] temp = hyp[j]; 
      if (temp[0] == trainingexample[j]); 

     } 
    } 
} 
+0

該代碼不會編譯。 – m0skit0

回答

2

這將是最好的定義hyp爲一個多維數組。

static Object[][] hyp = {sky,airtemp,humidity,wind, water, forecast}; 

然後你的任務將工作:

Object[] temp = hyp[j]; 

或者,但不太清楚,你可以只投hyp[j]Object[],但我不會推薦它。

Object[] temp = (Object[]) hyp[j]; 
0

在特定索引j處的hyp將返回Object。

static Object[] hyp = {sky,airtemp,humidity,wind, water, forecast}; 

因此改變Object[] temp = hyp[j];Object temp = hyp[j];

+0

是的,我知道,但我需要能夠引用temp中的第一個元素,但temp只包含該數組的地址,所以我無法調用temp [0]。 – eager2learn