I need to create new variables Strings
such that
String person1 = "female";
String person2 = "female";
........
........
String person60 = "male";
........
String person100 = "male";
This is what I tried
for (int i = 1; i <101; i++) {
if (i<60) {
String person+i = "female";
}
else {
String person+i = "male";
}
}
Can anybody help me correct this code?
There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.
Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.
A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value
Map<String, String> details = new HashMap<>();
for (int i = 1; i <101; i++) {
if (i<60) {
details.put("person" + i, "female");
}
else {
details.put("person" + i, "male");
}
}
You are close. If you store the the gender of each person in an array, you can do it like this:
String[] persons = new String[100]
for (int i = 0; i < persons.length; i++) {
if (i<60) {
persons[i] = "female";
}
else {
persons[i] = "male";
}
}
Alternately, if a person is more than a gender, consider making a class Person
that holds a gender field, and then have an array of Person
s. You would set the gender in a similar way.
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