Print variables before looping

8

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 print the value of the above variables in for in this way or you can not because there you print a1, a2 and so and what I want is for you to print the value of a1 or aa .

Thanks x the help in advance

    
asked by Luis David Jimenez 08.08.2017 в 21:10
source

4 answers

3

What you are trying to do is to 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 that contains elements type String 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 by 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 within the array:

for(int i = 0; i<elementos.length; i++){            
        System.out.println("a"+i +"= "+elementos[i]);
}
    
answered by 08.08.2017 в 21:19
2

In a programming language like Java, what you try to do is not possible, and it does not make sense either .

The reason is that the names of variables only make sense at compile time, they are not available at runtime, or even through reflection.

In line String a5 = ("a"+ i); where you name the variable, it is a simple string that will be printed as such, in this line: System.out.println("a"+i +"= "+a5); so you get "a1" , "a2" , "a3" and "a4" .

By the time these lines are running, the java compiler will have converted the source code into bytecode long ago that do not retain the variable names and such variables are referenced by positions in the stack or cpu records.

    
answered by 08.08.2017 в 21:23
2

Code

package Interfaz;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Clase {

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

    public static void main(String[] args) {

        ClassLoader cargador = Clase.class.getClassLoader();
        Class clase;
        Object objeto;

        try {

            clase = cargador.loadClass("Interfaz.Clase");
            objeto = clase.newInstance();

            Field[] campos = clase.getFields();

            for (Field campo : campos) {
                Object valor = campo.get(objeto);
                System.out.println(valor);
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            Logger.getLogger(Clase.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

Result

run:
aa
bb
cc
dd

Explanation

Most programming languages have a concept known as the Reflexion , which consists in accessing certain elements, functions, methods, etc. Using references to these through their names .

What does this mean?

This suggests to us that there are languages in which you could easily do something like:

funcion(){
   return 1;
}

llamarFuncion("funcion");

Cases like these exist in PHP, C ++, Java, Etc.

Let's cut to the chase

Using the method getFields of Java, we can access all the variables whose visibility is public , therefore we make use of this function on the class Clase , obtaining from it all the variables declared, for this case, a1,a2,a3,a4 and there, being able to obtain their values later.

    
answered by 08.08.2017 в 22:18
0

Yes it can be done from a conceptual point of view.

You want to be able to associate values ("aa", "bb" ..) with some "variables" to which you give some names ("a1", "a2" ...). And you want to be able to access those "variables" by building your name dynamically.

I put variables in quotes because in the strict case of variables within a method, which are those that appear in your example, it is not possible, that I know, not even with reflection. But it is possible to have a mechanism that allows you to associate values with names. That mechanism is called MAP .

A map is an associative container. It comes to be like an array. But in an arrangement the access index can only be an integer, in a map it can be any type of data, and in the maps it is usually called key instead of index.

With the following code, we create a map that associates values of type ValidValue with keys of type TipoClave.

Map<TipoClave, TipoValor> var = new HashMap<>();

In our case we will use String as KeyType and String as ValidType.

To assign (or using the terminology of the maps associate ) a value to a key we use put. The first four lines of the original author's main would look like this:

Map<String, String> variables = new HashMap<>();
variables.put("a1", "aa");
variables.put("a2", "bb");
variables.put("a3", "cc");
variables.put("a4", "dd");

To read the value associated with a key we use the get method. The original author's code using maps would be:

for(int i = 1; i<=4; i++){
    String a5 = ("a"+ i);
    System.out.println("a"+i +"= "+ variables.get(a5) );
}
    
answered by 09.08.2017 в 18:58