Increment variable names? [duplicate]

。_饼干妹妹 提交于 2019-11-26 17:29:13

问题


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.


回答1:


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));
}



回答2:


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.




回答3:


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

int[] tacos = new int[numberOfTacos];
// in some loop or whatever
tacos[x] = someValue;



回答4:


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




回答5:


I TacoX is going to be an integer, I would create an array of X ints. If the max number is 10, we have:

int[] taco = new int[10];

Then to modify/read tacoX, you just look at taco[X]



来源:https://stackoverflow.com/questions/7762848/increment-variable-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!