Java Scanner Class Keyboard Class User Interaction So
Java Scanner Class Keyboard Class
User Interaction �So far when we created a program there was no human interaction �Our programs just simply showed one output �In order for users to interact with our programs we need to use external classes
External Classes �External classes are ready made classes that are used to allow users to interact with a program �Two examples of external classes are; 1. The Scanner Class 2. The Keyboard Class
Using External Classes �In order to use external classes you would need to let your program know that you would like to use them �In order to call ALL external classes you need to use the following code snippet import java. util. *;
Scanner & Keyboard Class �The scanner and keyboard classes are both used to allow users to interact with the program �They are used to ask users for an input �The input is normally done using the actual keyboard
Scanner Class �The first thing you need to do is create an instance of the Scanner class Class Name Creates an instance of the class Constructor
Scanner Inputs �You could input many different data types; Data Type Method String str = s. next(); double d = s. next. Double(); long l = s. next. Long(); short sh = s. next. Short(); byte b = s. next. Byte(); float f = s. next. Float(); boolean bo = s. next. Boolean();
import java. util. Scanner; Examples class test { public static void main (String args[]){ //Create an instance of the Scanner s = new Scanner(System. in); System. out. print("Enter your name : "); //Since the name is a String the String //has to be used String name = s. next(); System. out. println("How old are you ? "); //The age can be stored in a long age = s. next. Long(); System. out. println("You are "+name+" and you are "+age+" years old. "); } }
Keyboard Class �This class is also used to let users input data from the keyboard �The user can input the same data types we spoke about when we used the scanner class
Using the Keyboard Class Data Type Method int Keyboard. read. Int(); byte Keyboard. read. Byte(); short Keyboard. read. Short(); long Keyboard. read. Long(); float Keyboard. read. Float(); double Keyboard. read. Double(); char Keyboard. read. Char(); boolean Keyboard. read. Boolean(); Keyboard. read. String();
class test { public static void main (String args[]){ System. out. print("Enter your name : "); String name = Keyboard. read. String(); System. out. println("How old are you ? "); long age = Keyboard. read. Long(); System. out. println("You are "+name+" and you are "+age+" years old. "); } }
Which is better to use? Why?
- Slides: 12