0

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

Tharif
  • 13,794
  • 9
  • 55
  • 77
DoubtClear
  • 129
  • 1
  • 4
  • 11
  • 8
    Use an array... – Eran Aug 03 '16 at 07:36
  • 2
    Change the variables to an array (`int[] a = new int[4];`) and use `a[i-1]` instead of `a(i)` (because you loop from 1 to 4 but array indices are 0-based, i.e. from 0 to 3). – Thomas Aug 03 '16 at 07:37

2 Answers2

0

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

            }
     }

}
CloudPotato
  • 1,255
  • 1
  • 17
  • 32
0

you can use like this

   public class Main {
       public static void main(String... args) {
           int a[]={3,4,5};
           int result;
           for(int i=0; i<a.length;i++){
               result = a[i];
               System.out.println("Value of a(i): "+result );

           }
       }

   }

output:

Value of a(i): 3
Value of a(i): 4
Value of a(i): 5
jitendra varshney
  • 3,484
  • 1
  • 21
  • 31