[go: up one dir, main page]

0% found this document useful (0 votes)
8 views9 pages

Scanner

Java Program
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views9 pages

Scanner

Java Program
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Getting input from

keyboard
SCANNER

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
import java.util.Scanner;
or
import java.util.*;

Import java.util.scanner is like using scanner


function from utility package which has a
scanner class which takes input from user.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// takes input from the keyboard
String name = input.nextLine();
// prints the name
System.out.println("My name is " + name);
// closes the scanner
input.close();
}}
Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types.
import java.util.Scanner;
public class ScannerSample{
public static void main (String [] args){
Scanner sc = new Scanner ( System.in );

System.out.println(“ Enter User Name: “ );


String x = sc.nextLine ();
Sytem.out.println(“ User Name: “ + x);
}
}
Java Scanner nextInt()
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int data1 = input.nextInt();
System.out.println("Using nextInt(): " + data1);
input.close();
}
}
Java Scanner next()
import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String value = input.next();
System.out.println("Using next(): " + value);
input.close();
}
}
Java Scanner nextLine()
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String value = input.nextLine();
System.out.println("Using nextLine(): " + value);
input.close();
}
}

You might also like