2014-01-31 44 views
2

我想要寫一個句子是依賴於人的性別,這是我能做些什麼:Java字符串格式條件

String createSentence(String name, boolean isMale) { 
    return String.format(isMale ? "I met %s, he was OK." : "I met %s, she was OK.", name); 
} 

但你已經看到了失敗(它的工作原理,但代碼是duplicit ),我想要的東西是這樣的:

String createSentence(String name, boolean isMale) { 
    return String.format("I met %s, %b?'he':'she' was OK.", name, isMale); 
} 

這ofc不起作用,但是是這樣的可能嗎?

編輯:

因爲我將要生成許多句子,即使在不同的語言,它們將被保存爲某種或數組,因此這個解決方案是不方便:

static String createSentence(String name, boolean isMale) { 
    return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name); 
} 
+1

什麼不起作用? [你的例子完美地工作。](http://ideone.com/LXNdBd) – BackSlash

+0

你的第一個例子適合我。 – Pshemo

+1

是的,它*做*工作,但它產生了雙重性 – kajacx

回答

8

如何約

return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name); 

return String.format("I met %s, %s was OK.", name, (isMale ? "he" : "she")); 

如果你可以改變的isMale類型整數,例如將代表映射

  • 0 - >she
  • 1 - >he

你可以使用MessageFormat和其{id,choce,optionValue}

static String createSentence(String name, int isMale) { 
    return MessageFormat.format("I met {0}, {1,choice,0#she|1#he} is fine", 
      name, isMale); 

} 
+0

是的,這解決了這個問題,我簡化了這個問題太多了,我的apoligies,我會編輯這個問題。 – kajacx

0
String.format("I met %s, %s was OK.", name, isMale ? "he" : "she"); 
2

你可以去一個組合:

String createSentence(String name, boolean isMale) { 
    return String.format("I met %s, %s was OK.", name, isMale? "he": "she"); 
} 
0

你可以通過代詞本身再不用擔心任何條件。

static String createSentence(String name, String pronoun) { 
     return String.format("I met %s, %s was OK.", name, pronoun); 
} 

String sentence = createSentence("Fred", "he"); 

如果你需要使用布爾變量,你可以實現一個裝飾器。

-1

試試這個:

return "I met "+String.format(isMale ? " %s, he " : " %s, she ", name)+" was OK."