java – Printing variables before looping

Question:

I have the following code:

public static void main(String[] args) {

        String a1 = "aa";
        String a2 = "bb";
        String a3 = "cc";
        String a4 = "dd";

        for(int i = 0; i<3; i++){
            String a5 = ("a"+ i);
            System.out.println("a"+i +"= "+a5);
        }
}

I would like to know how you can somehow print the value of the above variables in the for that way or you can't because there it prints a1, a2 and so on and what I want is to print the value of a1 or aa .

Thanks for the help in advance

Answer:

What you are trying to do is evaluate "a"+ i , as if it were a variable for example a1 , a2 , etc. This is not possible:

 String a5 = ("a"+ i);

If you want to get the data printed, one option is to create an array containing String type elements and add these values.

  /* String a1 = "aa";
   String a2 = "bb";
   String a3 = "cc";
   String a4 = "dd";*/

    String[] elementos = {"aa","bb","cc","dd"};        

Remember that you can access the elements of an array through its index. For example:

  • elementos[0] will have the value "aa" .
  • elementos[1] will have the value "bb" .
  • elementos[2] will have the value "cc" .
  • elementos[3] will have the value "dd" .

To print them you would do it this way, accessing the values ​​inside the array:

for(int i = 0; i<elementos.length; i++){            
        System.out.println("a"+i +"= "+elementos[i]);
}
Scroll to Top