[英]Using arrays as elements of arrays
我在以下代碼中對方法“ update()”存在問題。 我試圖將數組用作“ hyp”數組的元素,因為各個數組的大小並不相同。 現在,在更新函數中,我想將存儲在各個數組的位置0中的元素(例如,在hyp的第j個位置的sky [0])與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]);
}
}
}
最好將hyp
定義為多維數組。
static Object[][] hyp = {sky,airtemp,humidity,wind, water, forecast};
然后您的作業將起作用:
Object[] temp = hyp[j];
或者,但不太清楚,您可以將hyp[j]
為Object[]
,但我不建議這樣做。
Object[] temp = (Object[]) hyp[j];
特定索引j的hyp將返回Object。
static Object[] hyp = {sky,airtemp,humidity,wind, water, forecast};
因此,更改Object[] temp = hyp[j];
到Object temp = hyp[j];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.