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);
}
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.
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);
}
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));
}
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With