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 ?
Asked
Active
Viewed 2,664 times
0
-
1Did 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. – Keppil Jul 02 '14 at 13:14
-
Yes i did. And weirdly it just skipped the part where it should take the input from the user and continued normally. I'm posting to see whether it's a problem with my code or just from java – Wassim Seifeddine Jul 02 '14 at 13:16
-
2Maybe you should consider posting your code to have an answer to this ? – Sharcoux Jul 02 '14 at 13:18
-
What do you mean by "*Can i use it to scan several inputs*"? Do you want to scan few sources/inputs or perhaps invoke few `nextXXX` methods on lets say `System.in` input stream? – Pshemo Jul 02 '14 at 13:18
-
1Also from your comments it seems that you may be facing problem described in [Scanner issue when using nextLine after nextXXX](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextxxx) – Pshemo Jul 02 '14 at 13:19
-
My code if of several classes. I have the main class which contains the scanner variable and several other classes are connected to it – Wassim Seifeddine Jul 02 '14 at 13:22
-
1We don't want you to post your entire code. Instead create [SSCCE](http://sscce.org/) - short but complete example which will let us reproduce your problem. – Pshemo Jul 02 '14 at 13:23
-
1Please, do not tag a question with whatever comes into your mind. There is no relationship to `eclipse`, `java-8`, `javac` or `javascript`. – Holger Jul 02 '14 at 13:58
1 Answers
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

user3717646
- 436
- 3
- 10

EJDinki
- 21
- 1