[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 353
  • Last Modified:

Variable in new variable name

im trying to use a for loop to create numbered variables without doing it by hand

for(int i=0;i<length;i++) {
Page#  where the # is the value of i
}

please post if this is possible and code to do it
0
JTWolfman
Asked:
JTWolfman
2 Solutions
 
bobbit31Commented:
that's what arrays are for:

int pages[length];

for (int i=0;i<pages.length;i++) {
   pages[i] = i;
}

System.out.println (pages[0]);
System.out.println (pages[1]);
System.out.println (pages[2]);
etc...
0
 
bobbit31Commented:
sorry, declaration should be:

int[] pages = new int[length];
0
 
JTWolfmanAuthor Commented:
ok, i need to be able to use the pages[#] as a variable name now, not just print them
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
bobbit31Commented:
pages[#] IS a variable
0
 
InNoCenT_Ch1ldCommented:
>>ok, i need to be able to use the pages[#] as a variable name now, not just print them

??
0
 
JTWolfmanAuthor Commented:
i need to be able to declare something like

String pages[#] = "Page";
0
 
JakobACommented:
Sorry, what you are describing are facilities you have in script languages, not in compiled languages like Java.
The upside of that is that Java programs run about 100 times faster than script programs.
But you cannot (at this time at least) have both.

would your need be filled by a static class with 2 methods in it.

  StC.setVar( name, value );   // name is a string (fx "Page"+2 ) and var may be a strin or an int or a float or ...
and
  Object n = Stc.getVar( name );  // give you back the variable value for that name in an object

That would be fairly easy to make using a hashmap.

regards JakobA
0
 
grim_toasterCommented:
How about declaring an Object to be held in your array,

private class Page {
  public String name;
  public Page(String name) {
    this.name = name;
  }
}

And declare your array as:

Page[] pages = new Page[length];

Then to set the page name use pages[i].name = "hello";

Or, create public get/set methods to access your name.  This approach also allows you to add other items to the page with very llittle effort on  your part!
0
 
JTWolfmanAuthor Commented:
thanks, i didnt know if it could be done without arrays, but with works so i split the points
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now