• A.razaq

T8- Scanner class

The Scanner class in java allows you to obtain an input from the user and in order to do that we need to implement the scanner class in our program

to implement the Scanner class in our program we do the following




import java.util.Scanner;


now we have imported the scanner class in our program we need to create an object of this class by using the keyword NEW



Scanner input = new Scanner (System.in);
  1. the first letter of Scanner is uppercase

  2. we name our object in this case its called input

  3. =

  4. New ( keyword to create a new object of the class scanner )

  5. class name which is Scanner

  6. System.in (standard input object)



now we have imported the scanner class and created an object from it , we are ready to use it

now lets make a simple program that takes integer input from the user and display them


first lets ask the user to enter their age by displaying the message using println method

System.out.println("Enter your age");

now we take the input from the user and in this case its an integer so lets make an integer variable named age and assign its value by the user input




int age = input.nextInt();

nextInt method to obtain an integer from the user at the keyboard

now lets display a message that shows the user input



System.out.println("Your age is :"+ age);

the final code will be



	Scanner input = new Scanner (System.in);
	
		System.out.println("Enter your age");
		int age = input.nextInt();
		System.out.println("Your age is :"+ age);

the output will be



so when we run the program the user will be asked to enter their age and after the user has entered their age , their result will be displayed

-----------

now lets try to obtain String input from the user


same as the previous steps



Scanner input = new Scanner (System.in);
	
		System.out.println("Ente your name");
		String name = input.next();
		System.out.println("Your name is :"+ name);

the only difference is in the input.next();

for string the method is next and for integer the method will be nextint and for double it will be nextDouble and so on


now the output of our program will be





2 views0 comments

Recent Posts

See All