我想要寫一個句子是依賴於人的性別,這是我能做些什麼: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);
}
什麼不起作用? [你的例子完美地工作。](http://ideone.com/LXNdBd) – BackSlash
你的第一個例子適合我。 – Pshemo
是的,它*做*工作,但它產生了雙重性 – kajacx