Hello, it became interesting, is it possible to use the values ​​of variables in the program code? The most commonplace examples:

  • Enter a string from the keyboard, for example, + or any other character of the operation. It is necessary to carry out the operation, the знак which was entered from the keyboard, and display the result on the screen. (Without using switch-case and any other cycles)
  • We have several variables, say, their names are foo_1 , foo_2 , ..., foo_10 . The number n is entered from the keyboard. It is necessary to display the value of the variable foo_ n . Again without switch-case and similar methods.
    Perhaps this is nonsense, but I have been interested in this question for a long time.

This is not a task, it is a personal interest. The question is how to use the values ​​of variables, whether strings or numeric variables, in the program code, and not comparing them with something and then performing actions.

Explanation for commentators.
Не нужно приводить примеры других циклов или способов сравнить значение введенной переменной и в зависимости от её значения выполнять что-то. Нужно именно встроить её значение в код. Например, чтобы использовать это для объявления переменных. Пусть, мне нужно объявить значение переменной, которая будет начинаться с foo_, а закончится введённым с клавиатуры значением и никак иначе.

For example, we enter several String variables from the keyboard: odin , test , foo . We fill them with some arr array. Also, we have the variables foo_odin , foo_dva , foo_tri , foo_test , foo_foo . Is there any way to implement access to variables as follows:

 for (String n : arr) System.out.println("foo_" + n + " = " + foo_..n) 

Here by means of .. I have marked the complement of the name of a variable by means of another variable. Suppose if we have the variable foo_odin and the variable n with the value odin , then, if we turn to foo_..n , we will call foo_idin .

  • Use reflection if there is no possibility to describe if / else switch / case - GenCloud
  • You did not understand the essence of the question. This is not someone's task. There is an opportunity to use anything, but not this. But if you want it that way - the use of any cycles and other things is prohibited. You need to directly use the value of variables in the program code, and not compare them, and then do something. - Peter Samokhin

4 answers 4

To access variables by their keyboard name, you can use the Java Reflection API . Here an example, I think, will understand:

 import java.lang.reflect.Field; import java.util.Scanner; class Foo { public float foo_1 = 1.1f; public int foo_2 = 2; public String foo_3 = "foo"; private int foo_4 = 100; } public class Main { public static void main(String[] args) { final Foo foo = new Foo(); final Scanner in = new Scanner(System.in); for (;;) { final String input = in.next(); if ("q".equals(input)) break; final String fieldName = "foo_" + input; try { final Field field = foo.getClass().getDeclaredField(fieldName); System.out.println("foo." + fieldName + " = " + field.get(foo)); } catch (final NoSuchFieldException e) { System.out.println("No field \"" + fieldName + "\"!"); } catch (final IllegalAccessException e) { System.out.println("Illegal access to field \"" + fieldName + "\"!"); } } } } 

Result of performance:

 1 foo.foo_1 = 1.1 2 foo.foo_2 = 2 3 foo.foo_3 = foo 4 Illegal access to field "foo_4"! 5 No field "foo_5"! q Process finished with exit code 0 
  • In this way, it may be possible to implement most of the ideas on the implementation of what I asked, but this implementation is not simpler than the usual one through cycles, and therefore - as I understand it - there is no concrete answer to my question. - Peter Samokhin

You can calculate a string with mathematical symbols like this:

 import java.util.*; import java.lang.*; import java.io.*; import javax.script.ScriptEngineManager; import javax.script.ScriptEngine; /* Name of the class has to be "Main" only if the class is public. */ class Test{ public static void main(String[] args) throws Exception{ ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String foo = "40+2"; int a = Integer.parseInt(engine.eval(foo).toString()); System.out.println(a); } } 

The answer is taken from here: https://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form

I added a cast to int.

  • I gave only a narrow, concrete example, and your answer also narrowly answers it, with a concrete example. I wanted to learn a little more. Or, at least, is there the same answer for my second example? - Peter Samokhin
  • Well, this example works with all four arithmetic operations. Didn't you need it? And about the second, why not write variables to an array and not output by index? - Kirill Malyshev
  • No, I did not need it. Read the question again, please, I supplemented it a little and explained. I do not need a specific example of performing arithmetic operations. I need another, and this I gave as an example, so that it is clear what I am asking. But thanks for this example too. - Peter Samokhin

Variables can be stored in the map <Srtring varName, Object o> and jerked by name, which can also be parsed and changed as you like.

The if / else / switch / case heap structure can be replaced with Enum. Each element in this enum is set its own symbol and override for each method with action. Then it will be possible to trigger an action on enum, and not through a bunch of conditions. But, IMHO, the code will be even more, although it will be moved to a separate place.

  • Increasing the length of the code is not the best solution, which can be :) I wanted to achieve, just, simplify the work with the program. For example, I have an array with several numbers. I need to display all the lines with the names foo_n , in which n are contained in the existing array. The easiest way would be to do it like this: for (int n : myArray){ System.out.println("foo_" + n + " = " + foo_..n); } Just something like that I would like to see. - Peter Samokhin

It is necessary to embed its value in the code. For example, to use it to declare variables.

Embed the value of a variable in the code - this is the assignment of its value to initialize the declared variable. And what's the problem? What is there not clear? Of course, you can use the value of a variable in the code, in particular, assign its value to another variable or add its value in the string by concatenation. Or not again?

  • It is necessary, for example, to supplement the name of a variable when it is initialized with the value of the variable entered from the keyboard. Suppose there is always foo_ at the beginning, and then what we enter follows. Enter test - will be foo_test . - Peter Samokhin
  • In no case. You can not do it this way. It would have earlier on a specific question. - Prapor Pr
  • The name is given once at the announcement and can not consist of fragments of lines. And logically, how to assign a value to a value is nonsense. - Prapor Pr