unaumamicorn Posted November 24, 2019 Share Posted November 24, 2019 In this tutorial myObj was being created as a new object referring to the input stream Scanner(System.in) I have a question on that - why can't we just use Scanner.nextLine() whenever we want to get user input if this is predefined method in package imported (similar to printf in C)? Thanks Link to comment Share on other sites More sharing options...
Ingolme Posted November 25, 2019 Share Posted November 25, 2019 Which tutorial are you referring to? Link to comment Share on other sites More sharing options...
Makwana Prahlad Posted April 14, 2020 Share Posted April 14, 2020 (edited) Hello, @unaumamicorn Please try this code,To Why do we have to create a new object to get user input but not use Scanner.nextLine() directly? Think of the class Scanner as a blueprint. It can read data input from not only the Keyboard, but also Files, and other Sources that have InputStreams, like a network connection. Due to its varied uses, Scanner has to be told which source to read from. import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); char gender = sc.next().charAt(0); System.out.println("Name: " + name); System.out.println("Gender: " + gender); } } System.in tells the scanner to read the data from the keyboard. You could provide a file or another InputStream and the Scanner read from there. I hope this information will be usefull for you. Thank you. Edited April 14, 2020 by Makwana Prahlad Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now