我想要写一个句子是依赖于人的性别,这是我能做些什么: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