0

Suppose , I have some variables as :

String x="abcd";
String y="qwert";
String z="mnvji";

and more...

I take an input from user. If user inputs 'x' , I print that string i.e. I print "abcd" If user inputs 'y' , I print "qwert" and so on... Is there any way to do it without switches or ifs??

Thank you,friends, in advance.

Arghya Chakraborty
  • 433
  • 1
  • 3
  • 12
  • Are these variables properties of a class or variables within a method? If they are properties, you could use reflection (even if it's not recommended). Otherwise, you just can't (see [this question](http://stackoverflow.com/q/744226/1225328)). In that case, you should consider @dacwe answer. – sp00m Aug 29 '12 at 11:38

9 Answers9

6

You could create a map from input string to result. Initialize the map:

Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");

And when you want to print the result from the input from the user:

Scanner s = new Scanner(System.in);

while (s.hasNextLine())
    System.out.println(map.get(s.nextLine()));
dacwe
  • 43,066
  • 12
  • 116
  • 140
4

Local variable names aren't available at runtime and reading field knowing it's name requires some reflection (see @amit's answer). You need a map:

Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");

Now just take value from that map:

String value = map.get(userInput);

value will be null if it doesn't match any of x/y/z.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • I don't like the first statement. The reflection API is very simple to use. I do agree it is not *advised* - but it is fairly *easy* to get a value by the field name. (I added a 2 lines example as an answer to show how it can be done) – amit Aug 29 '12 at 11:47
  • 1
    @amit: well, I wouldn't use reflection in "*normal*" Java program, maybe in library or framework. But that's not the point. OP says "*some variables*" and I am also talking about (local) variables, not about fields. – Tomasz Nurkiewicz Aug 29 '12 at 11:50
  • *local* variables are a different story, you should clarify it *explicitly* in your answer, IMO. – amit Aug 29 '12 at 11:52
2

As we can approach like that also,

String input[]=new String['z'];
 input['X']="abcd";
 input['Y']="qwert";
 input['Z']="mnvji";
 System.out.println(input['X']);

But it will come under some limitation

Sivaraman
  • 61
  • 7
  • +1; Simple. But range checks must be performed but I guess that is what you mean by *limitation*. And you could easily do `input['x'] = input['X'] = "abcd";` to put same data into several slots. – maba Aug 29 '12 at 12:21
1

Map collection using key value pair implementation solve your problem .

put varible x,y,z as key and "abcd" ,.. as value.

Retrieve value from specific key according to input value.

Map<String, String> map = new HashMap<String, String>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");

to get value

String value = map .get(inputValue).

Mohammod Hossain
  • 4,134
  • 2
  • 26
  • 37
0

Put your variable set into a HashMap as (key,value) pairs and just retrieve the value for the particular key when user inputs the key.

Anuruddha
  • 1,367
  • 6
  • 19
  • 38
0

create an string array in which x,y,z should be indexes and store the content relatively ...

get the user input and pass it to the array as index ..you will get it..

Aravindhan
  • 3,566
  • 7
  • 26
  • 42
0

If you have no choice but using object variables (fields) and not a Map as suggested by other answers - you might want to use reflection, and specifically the Class.getField() and Class.getDeclaredField() methods-

Field f = MyClass.class.getDeclaredField("x");
System.out.println(f.get(myObject));

Where MyClass is your class name and myObject is the object you want the value from.

Note that with this approach - you cannot add fields - you can only get existing ones.

amit
  • 175,853
  • 27
  • 231
  • 333
0

If you really don't want to use switches or ifs (and I'd assume you include maps in that) then you'd have to use reflection to get the names of all the variables and decide which to print on them. Here's the basics:

Class yourClass = Class.forName("yourpackagename.YourClassName")
Field[] allFields = yourClass.getDeclaredFields();
String[] fieldNames = new String[allFields.length];
for(int i = 0; i < fieldNames.length; i++)
{
   fieldNames[i] = allFields [i].getName();
}

//Get name of field user wants to display, and look it up in
//the fieldNames array to get the index of it, store this index

Object instance = yourClass.newInstance();
System.out.println(allFields[indexToDisplay].get(instance));

Of course, this could well be overkill.

MrLore
  • 3,759
  • 2
  • 28
  • 36
0
Map<String, String> map = new HashMap<>();
map.put("x", "abcd");
map.put("y", "qwert");
map.put("z", "mnvji");
Scanner s = new Scanner(System.in);
while (s.hasNextLine())
System.out.println(map.get(s.nextLine()));

will probably work.

Site Helpers
  • 227
  • 1
  • 4
  • 8