Reputation: 12939
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?
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);
}
Upvotes: 10
Views: 15226
Reputation: 4320
How about using an 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));
}
Upvotes: 1
Reputation: 124225
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
0
->she
, 1
->he
you could use MessageFormat and its {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);
}
Upvotes: 22
Reputation: 18177
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.
Upvotes: 0
Reputation: 4923
Try this :
return "I met "+String.format(isMale ? " %s, he " : " %s, she ", name)+" was OK."
Upvotes: -2
Reputation: 2830
String.format("I met %s, %s was OK.", name, isMale ? "he" : "she");
Upvotes: 1
Reputation: 5085
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");
}
Upvotes: 3