DoubtClear DoubtClear - 4 months ago 106
Java Question

How can I create variables A1, A2,...,A10 in a loop and gets its value in java

Suppose my code is

public class GetValueInLoop{

public static void main(String[] args) throws InterruptedException {
int a1=3;
int a2=4;
int a3=5;
int result;

for(int i=1; i<4;i++){
result = a(i);
System.out.println("Value of a(i): "+result );

}
}


How can I get output like

Value of a1:3
Value of a2:4
Value of a3:5


Can anyone help me out
Thanks

Answer

You better use an array:

public class GetValueInLoop{

    public static void main(String[] args) throws InterruptedException {
        int[] a= {3, 4, 5};

        for(int i=0; i<a.length;i++){
            System.out.println("Value of a(" + (i+1) + "): " + a[i]);

            }
     }

}