Scanner class in JAVA


Scanner class is used to take input from the user in java. It has many different methods to handle other task too. To use Scanner class you have to use import java.util.Scanner;  then you have to create an object of Scanner class. After creating an object, you can use the scanner object to store variables from user. When user gives input it stores in it and later on we can assign the value in variable for further use. let't see one example of Scanner class. Here, how to calculate Simple Interest is displayed. Source code...
package oop;

import java.util.Scanner;

public class ScannerDemo {

// Scanner is a class, located inside java.util package

// Scanner is used to take input from user in console

public static void main(String[] args) {

int t;
double p, r;

double si;

Scanner in = new Scanner(System.in);
System.out.println("Principle amount:");
p = in.nextDouble();
System.out.println("Enter rate:");
r = in.nextDouble();
System.out.println("Enter time:");
t = in.nextInt();

si = (p * t * r) / 100;

System.out.println("Simple interest: " + si);

}
}


==========================output:===============================

Principle amount:
100
Enter rate:
10
Enter time:
1
Simple interest: 10.0

=================================================================

After declaring variable, we have store data according to its datatypes. So, to store principle and rate in.nextDouble(); function is used because it takes input as a double datatype and to store time in integer format so in.nextInt() is used and stores the data into integer format. 

Then, simple interest is calculated and displayed to the user. (formula: p*t*r / 100)

See video here: https://youtu.be/DTp72p8TA4k



Comments

Popular posts from this blog

Logical operator in JAVA

Class and Object in Java

Loop Structure