2013-01-14 33 views
-3

我需要遍歷矩陣中的每個元素(如結構)。例如,從字符串形成一個值序列

SeatingType Model Back Mech 
1    6 120 58 
       7 121 59 
       8  

在java中的值將被作爲未來參數作爲字符串中逗號分隔值例如SeatingTpe(1),模型(6,7,8)等等

我需要得到的結果作爲

1,6,120,58 
1,6,120,59 
1,6,121,58 
1,6,121,59 
1,7,120,58 
1,7,120,59 
1,7,121,58 
1,7,121,59 
1,8,120,58 
1,8,120,59 
1,8,121,58 
1,8,121,59 

請注意,模型,返回和機甲可以null.So的情況下,模型值是零,那麼輸出應該是1,6,58和1,6,59等。任何幫助plz

作爲一個headstart,我嘗試了從最後一個元素(在這種情況下'Mech')循環>>但這是非常乏味。任何其他方法?我只在這裏提供了4個屬性。但是需要11個屬性。我希望如果我能爲4個atributes得到解決方案,即可以通過4個循環應用於其餘7

+0

你嘗試張貼問題之前,什麼? – Egor

+0

作爲一個頭馬,我試着從最後一個元素(在這個例子中是'Mech')循環遍歷。>但是這非常單調乏味。任何其他方法? –

+1

遞歸適合像手套一樣的問題。 –

回答

1

迭代:

List<String> seatTypeValues = ... 
List<String> modelValues = ... 
List<String> backValues = ... 
List<String> mechValues = ... 

if (seatTypeValues.isEmpty()) { seatTypeValues.add(null); } 
... // all 4 lists 

for(String seatType : seatTypeValues) { 
    for(String model : modelValues) { 
    for(String back : backValues) { 
     for(String mech : mechValues) { 
     // print the CSV 
     if (seatType != null) { 
      writer.write(seatType); 
     } 
     if (model != null) { 
      writer.write(','); 
      writer.write(model); 
     } 
     if (back != null) { 
      writer.write(','); 
      writer.write(back); 
     } 
     if (mech != null) { 
      writer.write(','); 
      writer.write(mech); 
     } 
     writer.write("\r\n"); 
     } 
    } 
    } 
} 
+0

Hi @Gabor。如果模特或背部是空的,該怎麼辦?我們如何處理。不輸入循環儀式 –

+0

行'if(seatTypeValues.isEmpty()){seatTypeValues.add(null); }'將爲列表添加一個空值,它將進入一次循環。 – gaborsch

+0

你會接受答案嗎? – gaborsch