0

Is there any way that can you print a variable using user input? I mean for example if the user input is "A" and I have a variable A = "something" in my code. how to print the variable using the user input "A"?

I've use char for this but it give me A not something.

String A = "something";

System.out.print("Input A");
String userInput = new Scanner(System.in).nextLine();

System.out.print(userInput);

I expect the output will "something", but the actual output is "A".

Johnny Mopp
  • 12,641
  • 5
  • 36
  • 62

2 Answers2

0

If I get this right, you want to be able to handle longer user input "commands" and then print a message according to the input?

You could use a...

Map<String, String> messages = new HashMap<String, String>();
messages.put("something", "this is a message");
// ...and so on... just add all you need.

...and then:

if (messages.contains(input)){
    System.out.println(messages.get(input));
} else {
    System.err.println("\"" + input + "\" is not a valid input value";
}

Explanation: A map stores key-value pairs of arbitrary types. You can define the types to use in the generics notation (here it is <String, String>). In your case, both the key and the value would be strings. They could be any other complex type.

bkis
  • 2,400
  • 1
  • 18
  • 26
0

You could use a switch, depending on how complex the user input will be (JDK 7 or greater):

String A = "...";
String B = "...";
String C = "...";

switch(userInput){
        case "A":
            System.out.println(A);
            break;
        case "B":
            System.out.println(B);
            break;
        case "C":
            System.out.println(C);
            break;
        default:
            System.out.println("...");
}
ck1221
  • 1,551
  • 1
  • 10
  • 17