Jump to content

Why do we have to create a new object to get user input but not use Scanner.nextLine() directly?


unaumamicorn
 Share

Recommended Posts

  • 4 months later...

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 by Makwana Prahlad
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...