baba ramdev baba ramdev - 24 days ago 12
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

This is a use case for an array:

String nums[] = new String[] {
    "blah1",
    "blah2",
    "blah3",
    "blah4",
    "blah5"
}

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++) {
   System.out.println(nums[i]);
}

More about arrays on Stack Overflow documentation.


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

Comments