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".

001
  • 13,291
  • 5
  • 35
  • 66
  • Why would you expect the output to be `something` if you enter `A` an print exactly this value back out? – QBrute May 14 '19 at 16:15
  • You are printing the `userInput` var, not the `A` var. Did you mean: `System.out.print(A);`? – 001 May 14 '19 at 16:15
  • yes sir that's why I'm asking on how to print something using that user input is there any way to do that ? – Jerico navarro May 14 '19 at 16:17
  • Check out the `reflect` package. In particular `this.getClass().getDeclaredField(userInput)` – Robert Kock May 14 '19 at 16:18
  • Ah, I get it, now. You want the user to enter the name of the variable to print. – 001 May 14 '19 at 16:26
  • Check this page https://stackoverflow.com/questions/5287538/how-can-i-get-the-user-input-in-java –  May 14 '19 at 16:26

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,530
  • 1
  • 17
  • 31
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("...");
}
Chris K
  • 1,581
  • 1
  • 10
  • 17