Scanner class in java

Scanner class in Java Part . 10

Scanner class in Java

How to take Input user in Java?

In order to read data from the keyboard, java has a Scanner class.

Scanner class has a lot of methods to read the data from the keyboard.

We have different ways to take input from user in Java.

There are three different ways to take input from user.

1 :- Scanner class    (Present in import java.util.Scanner; package)

2 :- Buffered Reader class    (Present in java.io package)

3 :- System.i.read()

Scanner class is easiest way to take input from user in all among ways.

Scanner class (Present in java.Util package)

It is predefined class.

1 :- Scanner class is used to take input from keyboard, File, Network.

2 :- Scanner class is present in java.util package.

3 :- Scanner class provides us various methods (functions) to take different type of data from user.

i.e. :- next(), nextInt(), nextFloat(), nextLine(), nextChar(), . . . . . . . . . . . . . . . . . . . . .

4 :- Scanner class is final class means we can not create child classes from it.

5 :- Scanner class not have zero parameter constructor (default constructor).

How to use the predefined class

1 :- to consume any class first you have to create object of that class.

i.e. :- Scanner sc=new Scanner(System.in);   à  (Read from the keyboard)

int a=sc.nextInt();  à   [Method to read from the keyboard  (Int in this case)]

2 :- By using reference variable we can access all the methods present in that classes with .(dot)operator.

i.e. :- sc.nextint();

How to use Scanner class i.e. :-

Two number addition program in java using Scanner function :-

import java.util.*;
public class Test
{
public static void main(String[]ar)
{
int a,b,c;
System.out.println(“Enter Two Number : “);
Scanner s=new Scanner(System.in);
System.out.println(“Enter the Number a : “);
a=s.nextInt();
System.out.println(“Enter the Number b : “);
b=s.nextInt();
c = a+b;
System.out.println(“Sum is :”+c);
}
}

Scanner class code output

Rating: 5 out of 5.

Now Friends If you like this post please tell us how can we help you to provide better knowledge?

If this post is use full for you please share the post with your friends.

Please follow as facebook : www.facebook.com

Please follow as twitter : www.twitter.com

And more information please visit here : www.weindians.in

Please Subscribe on youtube : www.youtube.com

Leave a Reply

Your email address will not be published.

%d bloggers like this: