How to dynamically call a variable based on another variable in java

22
August 21, 2019, at 03:30 AM

I have an assignment and to simplify the code I would like to be able to reference a String based on the value of an int.

//Below is a rough example of what I'm trying to accomplish.
String player1Piece = "x";
String player2Piece = "O";
int playerturn; //Assigned value of either 1 or 2 later in code.
...
System.out.println(player(playerturn)Piece);

Let me know if this is at all possible but if not my current solution would be to use a switch statement and just copy and paste the output code.

Answer 1

Java is a compiled language, and does not have an eval function. You could use a simple if - else like

if (playerturn == 1) {
    System.out.println(player1Piece);
} else {
    System.out.println(player2Piece);
}

or you could store the pieces in an array, and access the array by index. Like,

String[] pieces = { "X", "O" };
// ...
System.out.println(pieces[playerturn - 1]);

note that arrays are indexed from 0 (so playerturn - 1 is necessary if you want to use the values 1 and 2).

or you could store the pieces in a map, and access the map by key. Like,

Map<Integer, String> map = new HashMap<>();
map.put(1, "X");
map.put(2, "O");
// ...
System.out.println(map.get(playerturn));

note that with a Map the playerturn value can be used without modification.

READ ALSO
Compare 2 identical excel/ppt/csv files in nodejs

Compare 2 identical excel/ppt/csv files in nodejs

I have a requirement where I want to compare 2 identical excel/ppt/csv files which may have exact same content but may be created at different point in time

55
Pm2 cluster + socket.io+ node.js

Pm2 cluster + socket.io+ node.js

I have my current application set up using node js, socketio and forever

24
Access variable from sync and async in nodejs

Access variable from sync and async in nodejs

I'm creating a nodejs server that has to do a few things:

52
How to handle promises in nested loop

How to handle promises in nested loop

I have an array of objects like this:

21