Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment variable names? [duplicate]

Okay so for what I am doing i need to increment my variables name, so for example int Taco1 = 23432..... int Taco2 = 234235656..... int Taco3 = 11111.......

But instead i need it to be a variable like

 int X = 0;
 some method with loop or recursion()
 int Taco(X) = bla bla bla
 x++

Trying to get my variable names to auto name themselves incremented by 1 every time, so they don't overwrite themselves. If this is impossible then my apologies.

like image 464
CMOS Avatar asked Oct 14 '11 03:10

CMOS


4 Answers

You can't do this in Java and more importantly, you don't want to do this as this isn't how Java works. In fact variable names aren't nearly as important as you think and hardly even exist in compiled code. What is much more important is that you are able to get a reference to your objects in as easy and reliable a way as possible. This can involve an array, an ArrayList (likely what you want here), a LinkedList, a Map such as a HashMap, a Set, and other types of collections.

For example:

List<Taco> tacoList = new ArrayList<Taco>();
for (int i = 0; i < MAX_TACOS; i++) {
   tacoList.add(new Taco(i));
}
like image 154
Hovercraft Full Of Eels Avatar answered Oct 17 '22 06:10

Hovercraft Full Of Eels


Indeed it is impossible to generate identifier names based on a variable. Perhaps what you want is an array:

int[] Taco = new int[ 15 /*some appropiate upper limit*/ ];

Taco[X] = bla bla bla;

Search the web for basic information on what arrays are and how they work.

like image 30
K-ballo Avatar answered Oct 17 '22 05:10

K-ballo


Use an int[] or a List<Integer>:

int[] tacos = new int[numberOfTacos];
// in some loop or whatever
tacos[x] = someValue;
like image 2
ColinD Avatar answered Oct 17 '22 06:10

ColinD


use array of int. say int taco[50]; and you can reference each location as taco[0],taco[1] etc

like image 1
COD3BOY Avatar answered Oct 17 '22 05:10

COD3BOY