2013-10-16 55 views
0

我有一個至少有三個元素的鋸齒狀數組,我需要解析出前五個元素,用空格填充任何空值。如何在Java中將鋸齒形數組解析爲單個變量?

// there will ALWAYS be three elements 
String whiconcatC = scrubbedInputArray[0]; 
String whiconcatD = scrubbedInputArray[1]; 
String whiconcatE = scrubbedInputArray[2]; 

// there MAY be a fourth or fifth element 
if (scrubbedInputTokens > 3) { 
String whiconcatF = scrubbedInputArray[3]; 
} else { 
String whiconcatF = " "; 
} 
// 
if (scrubbedInputTokens > 4) { 
String whiconcatG = scrubbedInputArray[4]; 
} else { 
String whiconcatG = " "; 
} 

雖然上面的代碼不會產生編譯過程中出現錯誤,隨後的行中引用whiconcatFwhiconcatG將錯誤輸出與cannot find symbol期間編譯。

我使用forEachStringTokenizer(數組轉換成字符串分隔後)嘗試過,但無法弄清楚如何在工作情況下的默認值是有斑點沒有價值4 & 5.

我一直無法找出任何其他方式來做到這一點,也沒有爲什麼我的邏輯如果失敗。建議?

+0

謝謝,大衛,它做到了。範圍問題。 – dwwilson66

+0

你可能想要初始化它們,以避免空指針異常。 –

+2

@david - 您應該避免編輯問題,以便修復錯誤本身。這會使下面給出的答案完全不相關。 – SudoRahul

回答

5

那是因爲它們具有局部範圍並且在括號內定義。因此,當你關閉方括號並且無法到達時死亡。在外面定義它們,你應該沒問題。

String whiconcatC = scrubbedInputArray[0]; 
String whiconcatD = scrubbedInputArray[1]; 
String whiconcatE = scrubbedInputArray[2]; 
String whiconcatF = ""; 
String whiconcatG = ""; 


// there MAY be a fourth or fifth element 
if (scrubbedInputTokens > 3) { 
whiconcatF = scrubbedInputArray[3]; 
} else { 
whiconcatF = " "; 
} 
// 
if (scrubbedInputTokens > 4) { 
whiconcatG = scrubbedInputArray[4]; 
} else { 
whiconcatG = " "; 
} 
4

if-else之外聲明whiconcatF,以便它們在其之後可見。目前,這兩個字符串變量僅在ifelse的範圍內。一旦它移動到if以上,它就會得到方法級別的範圍(我希望這個片段不在其他任何塊中),因此你可以在方法的任何地方訪問它們。

String whiconcatF = " "; // Default value 
if (scrubbedInputTokens > 3) { 
    whiconcatF = scrubbedInputArray[3]; 
} 

String whiconcatG = " "; // Default value 
if (scrubbedInputTokens > 4) { 
    whiconcatG = scrubbedInputArray[4]; 
} 

既然你有默認值現在,您可以同時爲if刪除else部分。

+0

看起來像有人已經對我的代碼....範圍進行了更改。它始終是範圍...;) – dwwilson66

+0

@MarounMaroun - 完成!:)在最初發布答案後,我已經離開了我的位置,因此無法立即清理! – SudoRahul

+0

@ dwwilson66--請不要鼓勵對這個問題進行編輯,因爲如果錯誤本身從問題中刪除,它不再是一個問題,所有爲此發佈的答案都變得無關緊要。希望你能理解。 – SudoRahul