User Input
User Input
1
User input in Java
● Sometimes we need to take input from the user.
● Creates a connection between the program and it’s user.
● Most common way to take input is using the java scanner class.
2
What is a Java Scanner Class?
● A predefined class that reads data from the keyboard or a text file.
● Found in the java.util package.
● Can read all types of data (numeric, strings and other data types).
● Easiest way to take input from the user.
3
User Input using Scanner class
● Import the java.util.Scanner package
● Create an object of the Scanner class
● Syntax:
To create an object
Class Name of Scanner class
Variable Name
To receive input
from user
4
Example
1. import java.util.Scanner;
2. class UserInput {
3. public static void main (String [] args){
4. Scanner sc = new Scanner (System.in);
5. String st1 = sc.nextLine();
6. System.out.println("Output: " + st1);
7. }
8. }
5
Inputting Different Datatypes
Method Usage
6
Inputting Integer Datatype
1. import java.util.Scanner;
2. public class UserInput {
3. public static void main (String [] args){
4. Scanner sc = new Scanner (System.in);
5. System.out.print(“Enter an integer: “);
6. int num1 = sc.nextInt();
7. System.out.println(“Output: ” + num1);
8. }
9. }
1. import java.util.Scanner;
2. public class UserInput {
3. public static void main (String [] args){
4. Scanner sc = new Scanner (System.in);
5. System.out.print(“Enter a boolean: “);
6. boolean bool = sc.nextBoolean();
7. System.out.println(“Output: “ + bool);
8. }
9. }
1. import java.util.Scanner;
2. public class UserInput {
3. public static void main (String [] args){
4. Scanner sc = new Scanner (System.in);
5. System.out.print(“Enter a string: “);
6. String st1 = sc.nextLine();
7. System.out.println(“Output: “ + st1);
8. }
9. }
1. import java.util.Scanner;
2. public class UserInput {
3. public static void main (String [] args){
4. Scanner sc = new Scanner (System.in);
5. System.out.print(“Enter a string: “);
6. String st1 = sc.next();
7. System.out.println(“Output: “ + st1);
8. }
9. }
11