Jump to content
Sign in to follow this  
unaumamicorn

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

Recommended Posts

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

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...