0

If i declared one scanner variable for a certain class in java. Can i use it to scan several inputs from the user ? For example at the beginning i want to scan an integer. The a double. And at the end a string. Will this work ?

8
  • 1
    Did you try it? If you did, what happened? If you didn't, please do and then reconsider if you need to ask us something or not. Commented Jul 2, 2014 at 13:14
  • 2
    Maybe you should consider posting your code to have an answer to this ? Commented Jul 2, 2014 at 13:18
  • 1
    Also from your comments it seems that you may be facing problem described in Scanner issue when using nextLine after nextXXX Commented Jul 2, 2014 at 13:19
  • 1
    We don't want you to post your entire code. Instead create SSCCE - short but complete example which will let us reproduce your problem. Commented Jul 2, 2014 at 13:23
  • 1
    Please, do not tag a question with whatever comes into your mind. There is no relationship to eclipse, java-8, javac or javascript. Commented Jul 2, 2014 at 13:58

1 Answer 1

2

Sure. A scanner could be reused just like any variable can and this avoids having to declare a new scanner each time we need to read new input. Scanner provides different methods for different types, so be sure to use the right one if you know what the input will be (you could take everything as a string alternatively).

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.next();

In the above, it will scan an integer, then a double, then a String.

see the documentation for more details , please scroll down to method summary section. It says how to get various types of inputs using scanner. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

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

Comments

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.