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 ?
1 Answer
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
eclipse,java-8,javacorjavascript.