baba ramdev baba ramdev - 1 year ago 86
Java Question

How to call multiple variable of string with numbering in loop?

What i am trying to achieve is, let's say I've these variables below:

String num1 = "blah1";
String num2 = "blah2";
String num3 = "blah3";
String num4 = "blah4";
String num5 = "blah5";

Now i want to create a single string variable which would iterate the all values of string's variable inside loop.

for(int i=0; i<=5; i++){
System.out.println(num+""+i); //I know, this would give me some errors. But i want to make something like this to call all string variables.

Here i want to print all the values of string's variable by using loop, How to achieve this?

Help would be appreciated!

Answer Source

This is a use case for an array:

String nums[] = new String[] {

And then you can easily iterate through the values (note that you don't need to duplicate the number of elements (5) ):

for(int i=0; i<nums.length; i++) {

More about arrays on Stack Overflow documentation.

Alternatively, you may use a List instead of an array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download