اتحاد طلبة هندسة الحاسوب والشبكات - المدونه الرسميه C.N.E : Object Oriented Programming Using Java-6

المشاركات الشائعة

Object Oriented Programming Using Java-6



Class Scanner & Data Input Using Keyboard



Sometimes, the need raises to enter data from user by keyboard.

In Java, you can enter data from keyboard by using the class Scanner. Class Scanner is a built-in class in Java, you can enter data if you make an object from this class.



As any other programming language, Java has libraries.

A library is a set of pre-defined classes packaged to simplify the work by saving time & effort.

To include a library in a Java program, the user should write import library_name;
Where library_name is intended to be the desired library.

Usually, importing a whole library is inefficient in terms of performance. The user doesn't need to import a whole library while he wants only one class.
To import a single class, you refer to it using the dot operator, which helps reaching a specified class through the libraries containing it.

Even though that you may write a program & run it without the need to import any library, Java has a default library imported implicitly in each program.

To import the class Scanner & then create an object, you better consider the following example which uses Scanner to enter the values of three double variables using keyboard.





Let as assume that the user has entered the values of X1,X2 & X3 as 1,2 & 3 respectively, the output is then:




As the example shows, the import statement is written before & outside the class.


In Java, it is a must to write each separated class inside a separated .class file, both must have the same name.

An object input is created from class Scanner to start entering data by keyboard.

System.in is used to let the system start entering the data by user.


In the statement import java.util.Scanner; java & util are libraries, a library inside a library.

The statements where the system interrupts to let the user enter data are:

X1 = input.nextDouble ();
X2 = input.nextDouble ();
X3 = input.nextDouble ();

Where nextDouble () is a method used to recieve double value entered from user. 
The method is a part of class Scanner, we called the method through object input.

We have many methods to enter data of different datatypes, we mention the following ones:

nextInt
() //to get the following integer

nextLong
() //to get the following long

nextFloat
() //to get the following float

nextLine
() //to get the following whole line


سامر المناصرة








< >

ليست هناك تعليقات:

إرسال تعليق