2017-08-29 43 views
0

所以我有這個減少功能:與開關串奇怪的錯誤的map-reduce的Java

public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { 
    for (Text value: values){ 
     Matrix matrix = new Matrix(value.toString()); 
     String name = matrix.get_name(); // Return "A" or "B" 
     context.write(key, new Text(name)); 
    } 

}

執行的代碼塊給我類似的信息(這是有道理的):

0,0 A 
0,1 A 
... 
0,0 B 
... 

然後,當我試圖切換 「名」 的價值:

public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { 
    for (Text value: values){ 
     Matrix matrix = new Matrix(value.toString()); 
     String name = matrix.get_name(); // Return "A" or "B" 
     switch (name){ 
      case "A": 
       context.write(key, new Text("AA")); 
       break; 
      case "B": 
       context.write(key, new Text("BB")); 
       break; 
      default: 
       context.write(key, new Text("CC")); 
       break; 
     } 
    } 
} 

上面的代碼給了我這樣的結果:

0,0 CC 
0,1 CC 
... 

我不明白的是爲什麼我switch語句確實在這種情況下工作(使用equals進行比較也不管用)

任何指針解決這個問題?

您的幫助將不勝感激。

//更新時間:

使用TRIM()和equalsIgnoreCase()不工作,要麼:

if ("A".equalsIgnoreCase(name.trim())){ 
    context.write(key, new Text("AA")); 
} 
else if ("B".equalsIgnoreCase(name.trim())){ 
    context.write(key, new Text("BB")); 
} 
else{ 
    context.write(key, new Text("CC")); 
} 
+0

最好使用if else和equals來代替switch語句,以確保編譯器使用equals methos來比較字符串。如果情況不重要,我還會推薦trim()和equalsIgnoreCase()。同時打印輸出,看看它爲什麼不等於你的A或B. –

+0

@KillerDeath你應該寫這個答案,因爲它幾乎肯定是正確的。 –

+0

是的,它必須是,沒有多少選擇這裏,THX諮詢 –

回答

1

不要在比較使用switch語句,使用TRIM()和equalsIgnoreCase()字符串當然還有其他的命令。

if(name.trim().equalsIgnoreCase("A"){...} 

else if name.trim().equalsIgnoreCase("B"){...} 
else ... 
+0

不工作,看到我更新 – Forrest

+0

當名稱應例如「A」,打印它,以便我們看到它是什麼。是否適當的「如果」觸發斷點? –