Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

SHAANTHI SCHOOL

LP-S8-CSC-Input using scanner class-22-23-1


Name of Teacher
Class S8 Subject Computer Science
Unit Chapter 4
Sub
Topic Input using scanner class
Topic
Date Day Hour

H1W1:
Learning Objectives:
 The students will know the scanner class and importing system package
 They will learn about Creating scanner object in java
 Different input functions using scanner class
H1W2:
Testing Previous knowledge
1. What is the main function using assignment class?

2. What is the different flow of control in java programming?

3. What is syntax errors?

H1W3:
PRESENTATION
The teacher explains the concepts

Scanner Class in Java

Scanner is a class in java. util package used for obtaining the input of the primitive types
like int, double, etc. and strings. It is the easiest way to read input in a Java program, though
not very efficient if you want an input method for scenarios where time is a constraint like in
competitive programming.

 To create an object of Scanner class, we usually pass the predefined object System.in,
which represents the standard input stream. We may pass an object of class File if we
want to read input from a file.
 To read numerical values of a certain data type XYZ, the function to use is nextXYZ().
For example, to read a value of type short, we can use nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function returns the next
token/word in the input as a string and charAt(0) function returns the first character in
that string.
Let us look at the code snippet to read data of various data types.

// Java program to read data of various types using Scanner class.

import java.util.Scanner;

public class ScannerDemo1

public static void main(String[] args)

// Declare the object and initialize with

// predefined standard input object

Scanner sc = new Scanner(System.in);

// String input

String name = sc.nextLine();

// Character input

char gender = sc.next().charAt(0);

// Numerical data input

// byte, short and float can be read

// using similar-named functions.

int age = sc.nextInt();

long mobileNo = sc.nextLong();

double cgpa = sc.nextDouble();

// Print the values to check if the input was correctly obtained.

System.out.println("Name: "+name);

System.out.println("Gender: "+gender);

System.out.println("Age: "+age);

System.out.println("Mobile Number: "+mobileNo);


System.out.println("CGPA: "+cgpa);

Input :

Geek

40

9876543210

9.9

Output :

Name: Geek

Gender: F

Age: 40

Mobile Number: 9876543210

CGPA: 9.9

Sometimes, we have to check if the next value we read is of a certain type or if the input has
ended (EOF marker encountered). Then, we check if the scanner’s input is of the type we
want with the help of hasNextXYZ() functions where XYZ is the type we are interested in.
The function returns true if the scanner has a token of that type, otherwise false. For
example, in the below code, we have used hasNextInt(). To check for a string, we use
hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

Let us look at the code snippet to read some numbers from console and print their mean.

// Java program to read some values using Scanner

// class and print their mean.

import java.util.Scanner;

public class ScannerDemo2

public static void main(String[] args)

// Declare an object and initialize with

// predefined standard input object

Scanner sc = new Scanner(System.in);

// Initialize sum and count of input elements

int sum = 0, count = 0;

// Check if an int value is available

while (sc.hasNextInt())

// Read an int value

int num = sc.nextInt();

sum += num;

count++;

int mean = sum / count;

System.out.println("Mean: " + mean);


}

In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly.

The import statement must be after the package statement, and before any other statement.

Using an import statement, we may import a specific class or all the classes from a package.

Importing specific class

Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.

Syntax

import packageName.ClassName;

Let's look at an import statement to import a built-in package and Scanner class.

Example

package myPackage;
import java.util.Scanner;
public class ImportingExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int i = read.nextInt();

System.out.println("You have entered a number " + i);


}}
In the above code, the class ImportingExample belongs to myPackage package, and it also
importing a class called Scanner from java. util package.
Practical’s – Laboratory:

Teacher Work-Classwork: Teacher will explain the scanner class in Java using BlueJ

H1W4:

Student Work-Classwork: Students will try to execute the programs in BlueJ

H1W5:
Student Work-Homework:
The students are asked to read and revise these topics in book and complete the check
points till taught.
H2W1:
Testing Previous knowledge
1. What is an importing system package?

2. What is the use of scanner class in java?

H2W2:
PRESENTATION
The teacher explains the concept.

Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types.

Method Description

nextInt() reads an int value from the user

nextFloat() reads a float value form the user

nextBoolean() reads a boolean value from the user

nextLine() reads a line of text from the user


next() reads a word from the user

nextByte() reads a byte value from the user

nextDouble() reads a double value from the user

nextShort() reads a short value from the user

nextLong() reads a long value from the user

Java Scanner with BigInteger and BigDecimal

Java scanner can also be used to read the big integer and big decimal numbers.

 nextBigInteger() - reads the big integer value from the user

 nextBigDecimal() - reads the big decimal value from the user

Working of Java Scanner

The Scanner class reads an entire line and divides the line into tokens. Tokens are small

elements that have some meaning to the Java compiler. For example,

Suppose there is an input string:

He is 22

In this case, the scanner object will read the entire line and divides the string into tokens:

"He", "is" and "22". The object then iterates over each token and reads each token using its

different methods.

Basic Math Functions

The java.lang.Math contains a set of basic math functions for obtaining the absolute value,
highest and lowest of two values, rounding of values, random values etc. These basic math
functions of the Java Math class will be covered in the following sections.
Math.abs()

The Math.abs() function returns the absolute value of the parameter passed to it. The
absolute value is the positive value of the parameter. If the parameter value is negative, the
negative sign is removed and the positive value corresponding to the negative value without
sign is returned. Here are two Math.abs() method examples:

int abs1 = Math.abs(10); // abs1 = 10int abs2 = Math.abs(-20); // abs2 = 20

The absolute value of 10 is 10. The absolute value of -20 is 20.

The Math.abs() method is overloaded in 4 versions:

Math.abs(int)

Math.abs(long)

Math.abs(float)

Math.abs(double)

Which of these methods are called depends on the type of the parameter passed to
the Math.abs() method.

Math.ceil()

The Math.ceil() function rounds a floating point value up to the nearest integer value. The
rounded value is returned as a double. Here is a Math.ceil() Java example:

double ceil = Math.ceil(7.343); // ceil = 8.0

After executing this Java code the ceil variable will contain the value 8.0 .

Math.floor()

The Math.floor() function rounds a floating point value down to the nearest integer value. The
rounded value is returned as a double. Here is a Math.floor() Java example:

double floor = Math.floor(7.343); // floor = 7.0

After executing this Java code the ceil variable will contain the value 8.0 .
Math.floorDiv()

The Math.floorDiv() method divides one integer (int or long) by another, and rounds the
result down to the nearest integer value. If the result is positive, the effect is the same as
using the Java / division operator described earlier in this text.

If the result is negative, however, the result is not the same. With the / division operator the
fractions are simply truncated. For positive numbers this corresponds to rounding down. For
negative numbers though, truncating the fractions correspond to rounding up.
The floorDiv() method rounds down to the nearest negative integer, instead of the rounding
up that would occur with fraction truncation.

Here is a Math.floorDiv() Java example:

double result3 = Math.floorDiv(-100,9);

System.out.println("result3: " + result3);

double result4 = -100 / 9;

System.out.println("result4: " + result4);

Math.min()

The Math.min() method returns the smallest of two values passed to it as parameter. Here is
a Math.min() Java example:

int min = Math.min(10, 20);

After executing this code the min variable will contain the value 10.

Math.max()

The Math.max() method returns the largest of two values passed to it as parameter. Here is
a Math.max() Java example:

int max = Math.max(10, 20);

After executing this code the max variable will contain the value 20.
Math.round()

The Math.round() method rounds a float or double to the nearest integer using normal math
round rules (either up or down). Here is a Java Math.round() example:

double roundedDown = Math.round(23.445);double roundedUp = Math.round(23.545);

After executing these two Java statements the roundedDown variable will contain the
value 23.0 , and the roundedUp variable will contain the value 24.0.

Math.random()

The Math.random() method returns a random floating point number between 0 and 1. Of
course the number is not fully random, but the result of some calculation which is supposed
to make it as unpredictable as possible. Here is a Java Math.random() example:

double random = Math.random();

To get a random value between 0 and e.g. 100, multiply the value returned
by Math.random() with the maximum number (e.g. 100). Here is an example of how that
might look:

double random = Math.random() * 100D;

If you need an integer value, use the round(), floor() or ceil() method.

Practical’s – Laboratory:

Teacher Work-Classwork: Teacher will explain the scanner class and mathematical
functions in Java using BlueJ

H2W3:

Student Work-Classwork: Students will try to execute the programs regarding


mathematical functions in BlueJ

H2W4:
Student Work-Homework:
The students are asked to read and revise these topics in book and complete the BBE fully.

You might also like