0

I am trying to use a user-entered number from the scanner in my code in multiple places. Below the line should be the same user-entered number as the first. Is this possible?

Scanner inputHere = new Scanner(system.in);
System.out.println("Please select me");
String inputHereOne = inputHere.nextLine();
System.out.println("----------------------------------");
6
  • Yes,it's possible. Commented Sep 22, 2019 at 0:12
  • You just want to use inputHereOne multiple times? Commented Sep 22, 2019 at 0:13
  • Do not forget to close your Scanner. Commented Sep 22, 2019 at 0:16
  • 1
    A stdin scanner does not necessarily need to be closed afaik. Commented Sep 22, 2019 at 0:18
  • @Carcigenicate is right, although in certain (rare and usually problematic) circumstances you might find yourself needing to do so. Commented Sep 22, 2019 at 0:20

1 Answer 1

1

Yes, it's possible. Use the value stored in inputHereOne. No need to call inputHere.nextLine() until you actually need the next line of input. Like so:

System.out.println(inputHereOne);
System.out.println(inputHereOne);

This will print inputHereOne, twice.

Sign up to request clarification or add additional context in comments.

2 Comments

@user9424843 That code will (line 1) create a Scanner reading from System input, (2) print "Please select me", (3) create a String variable inputHereOne with value equals to the next line from System input, and (4) print lots of dashes. After that code has run, you can use the value read into inputHereOne as you would like, by simply referring to inputHereOne. For example, to parse the int value out of inputHereOne, you might say something like int inputValue = Integer.parseInt(inputHereOne);. From then on, you could refer to the value as an int by referring to inputValue.
@user9424843 Please do some research. There are plenty of resources available on the site and Google to figure out how to do simple input reading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.