Course: Java Programming Prepared By: Atul Kabra, 9422279260
Java Lecture- 8
Topic: Reading Input from Console
Reading Input using Scanner class:
The Scanner class is used to get user input, and it is found in
the java.util package.
To use Scanner inside your program then you have to import
java.util package.
To use the Scanner class, create an object of the class and
use any of the following method to read primitive type of
input like int ,float etc.
Methods of Scanner Class
Method Description
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the
user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the
user
Course: Java Programming Prepared By: Atul Kabra, 9422279260
Course: Java Programming Prepared By: Atul Kabra, 9422279260
1. In the following program, we use different methods to read
data of various types:
import java.util.Scanner;
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Output
Course: Java Programming Prepared By: Atul Kabra, 9422279260
Course: Java Programming Prepared By: Atul Kabra, 9422279260
2. Program to read a number and then find its square
import java.util.*;
class Sqaure
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int n,s;
System.out.println("Enter the number ");
n= in.nextInt();
s=n*n;
System.out.println("Sqaure = "+s);
}
}
Output
Course: Java Programming Prepared By: Atul Kabra, 9422279260
Course: Java Programming Prepared By: Atul Kabra, 9422279260
3. Program to read two numbers and then print their addition.
import java.util.*;
class Addition
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int x,y,add;
System.out.println("Enter two numbers ");
x = in.nextInt();
y = in.nextInt();
add=x+y;
System.out.println("Addition="+add);
System.out.println("Addition of "+x+" and "+ y +" is "+add);
System.out.println(x + "+" + y +" = "+add);
}
}
Output:
Course: Java Programming Prepared By: Atul Kabra, 9422279260