Page 43 - CTS - CSA TP - Volume 2
P. 43

COMPUTER SOFTWARE APPLICATION - CITS



           EXERCISE 84 :  Read text from the keyboard using scanner

                                      class/ read text from the keyboard using
                                      console class



            Objectives

           At the end of this exercise you shall be able to
           •  should know  the use of scanner class/console class
           •  develop  java programs  using scanner class/console clas
           •  Compile, execute and verify the result of the Java Programs.


           Requirements

           Tools/Materials
           •  PC/Laptop  with Windows OS
           •  JDK Software
           •  Text Editor (Visual Studio/Sublime/Notepad)

            Procedure


           TASK  1:  Reading Text with Scanner Class Example_1
           import java.util.Scanner;
           public class ScannerExample {

               public static void main(String[] args) {
                   // Create a Scanner object
                   Scanner scanner = new Scanner(System.in);
                   // Prompt the user to enter a name
                   System.out.print(“Enter your name: “);

                   // Read the entered text as a String
                   String name = scanner.nextLine();
                   // Display a greeting
                   System.out.println(“Hello, “ + name + “!”);
                   // Close the Scanner

                   scanner.close();
               }
           }
           Step 1: Importing the Scanner Class








           This line imports the Scanner class from the java.util package. The Scanner class is used for obtaining user input
           from the keyboard.




                                                           28
   38   39   40   41   42   43   44   45   46   47   48