Day14: Using Scanner Class

 Using Scanner Class

We can use scanner class to take an input by the user. It is the second method while we take an input from the user. 
  • System.out.println()
  • System.in.read() ---> read will only accept char and show its unicode. Here "in" is object reference(taking input from keyboard) and "read" is method.

Scanner Method :

int---> int nextInt()
float ---> float nextFloat
double--->double nextDouble
String ----> next()
Byte ---> nextByte()
Long ----> nextLong()
boolean ---> nextBoolean()

Scanner S = new Scanner(System.in);

 

//Write a program to Add two number taking by user with the help of Scanner. 
import java.util.Scanner;

class AddNo
{
public static void main(String [ ] args)
{
//Create a Scanner object and connect it with kb
Scanner kb = new Scanner(System.in);
int a, b, c;
System.out.println("Enter First Number ");
a = kb.nextInt();
System.out.println("Enter Second Number ");
b = kb.nextInt();
c = a + b;
System.out.println("The Addition of two number 'a' and 'b' is "+c);
}
}

Output:


Accepting String Input

import java.util.Scanner;

class Greeting
{
public static void main(String [ ] args)
{
Scanner kb = new Scanner(System.in);
String name;
System.out.println("What is your name ");
name = kb.nextLine();
System.out.println("Hello "+name);
}
}
Output:


Using Character Input

import java.util.Scanner;
class Acceptor
{
public static void main(String [] args)
{
char ch;
String str;
Scanner sc = new Scanner(System.in);
str = sc.next();
ch = str.charAt(0);
System.out.println("You entered: "+ch);
}
}
Output > c

Second Method :

class Acceptor
{
public static void main(String [] args)throws Exception
{
char ch;
System.out.println("Enter a char: ");
                ch = (char)System.in.read();
                System.out.println("You entered "+ch);
}
}

Comments

Popular posts from this blog

What does System.out.printf( "%-15s%03d\n", s1, x) do?