GETTING INPUT FROM
THE USER
Prepared by: Ms. Jullie Ann M. Ocampo
1
Getting Input from the Keyboard
Two Methods On Getting Input From
The Keyboard
▪ Text-based (Scanner)
▪ Graphical User Interface
(JOptionPane)
2
Text-Based
Line 1, import Scanner for the Java Compiler
to recognize the Scanner class. This serves
as a library that contains methods to be used
in getting the input form the keyboard.
3
Line 3, we define the class named
TextBasedInput
Line 4, start of the main method
4
Line 5, display the string “Enter a number: “ in
the screen.
Line 6, instantiate the Scanner class and
store the object into the variable scan
5
Line 7, scan the value to be inputted form the
keyboard and store it to the variable num
using the method nextInt();
Line 8, display the string “You enter” together
with the value of num
6
Reading Different Data Types Using
Scanner
nextInt – to read int
nextFloat – reads float
nextLong – reads long values
nextDouble – reads double data type
nextLine – reads string
next – single word na string
7
GUI-Based
JOptionPane
▪ makes it easy to pop up a standard
dialog box that prompts users for a
value or informs them of something
▪ To use JOptionPane class we need to
import javax.swing.JOptionpane
8
Line 1, import the class JOptionPane inside
javax.swing
Line 3, start of the class GUIBasedInput
Line 4, start of main method
Line 5, showInputDialog will display a dialog
box with the string “Enter a number: ”
9
Input of the user will be store in variable input
Line 7, showMessageDialog will display a
dialog box that will display the string “You
enter ” with the value of input variable
10
Converting String to Numeric Data
Type
Integer.parseInt – converts String to int
Double.parseDouble – converts String to
double
Float.parseFloat – converts String to float data
types
Long.parseLong – converts String to long data
types
11