[英]Java string format condition
I want to write a sentence that is dependent on person's gender, here is what i could do:我想写一个取决于人的性别的句子,这是我可以做的:
String createSentence(String name, boolean isMale) {
return String.format(isMale ? "I met %s, he was OK." : "I met %s, she was OK.", name);
}
but you already see the fail in that (it works, but code is duplicit), i want something like:但你已经看到了失败(它有效,但代码是重复的),我想要这样的东西:
String createSentence(String name, boolean isMale) {
return String.format("I met %s, %b?'he':'she' was OK.", name, isMale);
}
This ofc doesn't work, but is something like this possible?这个 ofc 不起作用,但是这样的事情可能吗?
EDIT:编辑:
Since I will want many sentences to be generated, even in different languages, and they will be stored is some sort or array, thus this solution is unhandy:由于我希望生成许多句子,即使是不同的语言,并且它们将存储为某种类型或数组,因此此解决方案不方便:
static String createSentence(String name, boolean isMale) {
return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name);
}
How about怎么样
return String.format("I met %s, "+(isMale?"he":"she")+" was OK.", name);
or或者
return String.format("I met %s, %s was OK.", name, (isMale ? "he" : "she"));
If you can change type of isMale
to integer which for instance would represent mapping如果您可以将isMale
类型isMale
为整数,例如表示映射
0
-> she
, 0
-> she
,1
-> he
1
-> he
you could use MessageFormat and its {id,choce,optionValue}
您可以使用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);
}
You could go for a combination:你可以选择一个组合:
String createSentence(String name, boolean isMale) {
return String.format("I met %s, %s was OK.", name, isMale? "he": "she");
}
String.format("I met %s, %s was OK.", name, isMale ? "he" : "she");
How about using an enum
?使用enum
怎么样?
enum Gender {
FEMALE("she"), MALE("he") /* ... */;
private final String pronoun;
private Gender(String pronoun) {
this.pronoun = pronoun;
}
public String pronoun() {
return pronoun;
}
}
private static String createSentence(String name, Gender gender) {
return String.format("I met %s, %s was OK.", name, gender.pronoun());
}
public static void main(String[] args) {
System.out.println(createSentence("Glenda", Gender.FEMALE));
System.out.println(createSentence("Glen", Gender.MALE));
}
You could pass the pronoun itself and then not have to worry about any condition.您可以传递代词本身,然后不必担心任何情况。
static String createSentence(String name, String pronoun) {
return String.format("I met %s, %s was OK.", name, pronoun);
}
String sentence = createSentence("Fred", "he");
If you need to use boolean variables, you could implement a decorator.如果你需要使用布尔变量,你可以实现一个装饰器。
尝试这个 :
return "I met "+String.format(isMale ? " %s, he " : " %s, she ", name)+" was OK."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.