How to create variables dynamically in Java?
40603 просмотра
7 ответа
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?
Автор: Andrei Vasilev Источник Размещён: 12.11.2019 09:25Ответы (7)
20 плюса
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");
}
}
Автор: MeBigFatGuy
Размещён: 12.10.2013 03:59
9 плюса
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.
6 плюса
You might use a Map<String,String>
where the key is your "variable name" and the value is the value of that variable.
4 плюса
You will need a String[]
of some size that you can determine dynamically.
Then, assign values to the array elements.
String[] anArray;
// some magic logic
anArray = new String[100];
for(int i = 0; i < anArray.length; i++){
// more magic logic to initialize the elements
}
Another option is a Vector<>
or ArrayList<>
like so:
List<String> anExpandableArray = new ArrayList<String>();
// add String data
anExpandaleArray.add("Foo");
anExpandaleArray.add("Bar");
Автор: Little Child
Размещён: 12.10.2013 03:57
4 плюса
When you find yourself wanting to create "more variables" of the same type, you usually want a list of some kind. There are two fundamental kinds of "lists" in Java: Arrays, and List
s.
An array:
String[] people = new String[10]; // That gives you room for 10
people[0] = "female";
people[1] = "male";
// ...
int n = 1;
System.out.println("Person " + n + " is " + people[n]);
A List
:
List<String> people = new LinkedList<String>(); // Expandable
people.add("female");
people.add("male");
// ...
int n = 1;
System.out.println("Person " + n + " is " + people.get(n));
// Note difference -------------------------------^^^^^^^
Using an array is great when you know in advance how many there will be. Using a list is great when you don't know how many there will be.
Note on lists: There's an interface, List
, and then there are multiple different concrete implementations of it with different runtime performance characteristics (LinkedList
, ArrayList
, and so on). These are in java.util
.
3 плюса
Just Use an array like so
String[] people = new String[numofelements];
And to initialise the array
for(int i = 0; i < people.length; i++){
people[i] = "whatever";
}
Автор: 06needhamt
Размещён: 12.10.2013 03:57
3 плюса
String[] persons = new String[101];
for (int i = 0; i < 101; i++) {
if (i < 60) {
String persons[i] = "female";
} else {
String persons[i] = "male";
}
}
Автор: user278064
Размещён: 12.10.2013 03:58
Вопросы из категории :
- java В чем разница между int и Integer в Java и C #?
- java Как я могу определить IP моего маршрутизатора / шлюза в Java?
- java Каков наилучший способ проверки XML-файла по сравнению с XSD-файлом?
- java Как округлить результат целочисленного деления?
- java Преобразование списка <Integer> в список <String>
- java Почему я не могу объявить статические методы в интерфейсе?
- java Библиотека Java SWIFT
- java Выключение компьютера
- java Как я могу воспроизвести звук на Java?
- java Когда выбирать отмеченные и непроверенные исключения
- string В чем разница между строкой и строкой в ??C #?
- string Почему в Ruby нет реального StringBuffer или StringIO?
- string Преобразовать строку в перечисление в C #
- string Самый эффективный способ объединения строк?
- string Экранирование строк HTML с помощью jQuery
- string PHP эквивалент .NET / Java toString ()
- string Как отсортировать список строк?
- string Как сгенерировать случайную буквенно-цифровую строку?
- string Как разбирать строку в nullable int