Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Scanner input = new Scanner(System.in) actually mean?

Scanner input = new Scanner(System.in);

Could you give me a detailed explanation on what the code above is doing step by step? I don't really understand how it works and how it links to me later being able to do this statement:

int i = input.nextInt()
like image 523
The Man Avatar asked Jun 03 '15 06:06

The Man


People also ask

What is scanner SC new scanner system in in java?

The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.

What is scanner input?

1. When referring to hardware, a scanner, image scanner, or optical scanner is a hardware input device that optically "reads" an image and converts it to a digital signal.

How does scanner system in work?

Scanners work by converting the image on the document into digital information that can be stored on a computer through optical character recognition (OCR). This process is done by a scanning head, which uses one or more sensors to capture the image as light or electrical charges.


2 Answers

Alright, let's elaborate with some simplified explanation about the Scanner class.

It is a standard Oracle class which you can use by calling the import java.util.Scanner.

So let's make a basic example of the class:

class Scanner {
   InputStream source;

   Scanner(InputStream src) {
       this.source = src;
   }

   int nextInt() {
       int nextInteger;
       //Scans the next token of the input as an int from the source.
       return nextInteger;
   }
}

Now when you call Scanner input = new Scanner(System.in); you make a new object of the Scanner class (so you make a new "Scanner") and you store it in the variable input. At the same time you are calling the (so called) constructor of the class, with the parameter System.in. That means it is going to read from the standard input stream of the program.

Now when you are calling input.nextInt(); you execute the method from the object you just created (also documented). But as we see, this method returns a integer, so if we want to use that integer, we have to assign the call to a variable like you do:

int i = input.nextInt();
like image 149
moffeltje Avatar answered Oct 17 '22 13:10

moffeltje


Scanner input = new Scanner(System.in); creates a new Scanner instance which points to the input stream passed as argument. In your case the steam is Standard input stream.

So, once your scanner instance is pointing to it, you can scan the stream and get integers, strings and do other stuff .

like image 44
TheLostMind Avatar answered Oct 17 '22 14:10

TheLostMind