Scanner Class is the commonly used way of taking user inputs. There are many instances where user interaction is needed at runtime during the Program execution.

Scanner Class
- It can be used via java.util.Scanner library files.
- There is a major role of Whitespace and Enter while taking user inputs using Scanner class.
- These user inputs can be stored in any variable for future use.
- Most commonly methods are nextInt(), nextDouble(), nextBoolean(), next(), nextLine(), next(Pattern), hasNext(), hasNextLine() etc. from Scanner Class.
nextInt(): It takes only Integer values as input. Any other data type would result in an InputMismatchExecption. nextDouble(): It takes both Integer and decimal values as input. nextBoolean(): It takes user inputs only in TRUE and FALSE strings. These keywords are not case sensitive. Any other input would result in exception as mentioned above. |
All the above methods are very simple to use like given Examples:
import java.util.Scanner; /** * @author ashok.kumar * */ public class UserInput { public static void main(String[] args) { inputInteger(); // Takes input only in Integer format. inputDouble(); // Takes input in integer and decimal format. inputBoolean(); // Takes input only in TRUE and FALSE strings. } public static void inputInteger() { Scanner sc=new Scanner(System.in); System.out.print("Enter integer value: "); int temp=sc.nextInt(); System.out.println(temp); } public static void inputDouble() { Scanner sc=new Scanner(System.in); System.out.print("Enter decimal value: "); double temp=sc.nextDouble(); System.out.println(temp); } public static void inputBoolean() { Scanner sc=new Scanner(System.in); System.out.print("Enter Boolean value: "); boolean temp=sc.nextBoolean(); System.out.println(temp); } } }
next()
It takes string type of input but only the first word before the white space or end of line which encounters first. It takes only one word as input. Have a look in to the below example:
Scanner sc=new Scanner(System.in); String itemName=sc.next(); System.out.println(itemName); Input: TV Output: TV Input: TV Fridge AC Output: TV
nextLine()
It takes entire content till the end of line(Enter) not found to the compiler. While using the nextLine() make sure separate Scanner objects would be used for the same as it terminates whenever it finds any Enter or \n or End of Line.
Scanner sc=new Scanner(System.in); String storeAddress=sc.nextLine(); System.out.println(storeAddress); Input: A-56, Plot number 8 Output: A-56, Plot number 8
Related Links:
- Basic Java – 1 || Understand Java before start learning JAVA.
- Basic Java – 2 || Variables and Data Types used in JAVA.
- Basic Java – 3 || Understanding Class, Objects, Methods in Java.
- Basic Java – 4 || More on methods(Return Type and Parameters)
- Basic Java – 5 || Methods- Call by Value and Call by Reference in Java.
- Basic Java – 6 || Understanding of Constructor and Destructor in JAVA.
- Basic Java – 7 || Static Variables and Methods.
- Basic Java – 8 || Lets learn about Arrays in Java.
- Basic Java – 9 || Performing multiple operations using Java Operators.
- Basic Java – 10 || Conditions (If and Switch) in JAVA.
- Basic Java – 11 || for and for-each in Java. (Loops Part-1)
- Basic Java – 12 || Alternate looping concepts while and do-while. (Loops Part-2)
- Basic Java – 13 || Decimal values v/s Octal base(8) values in JAVA.
- Basic Java – 14 || Learn about String literals in Java.
- Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
- Basic Java – 16 || Runtime User Input using BufferedReader Class (Part-2).
- Basic Java – 17 || Runtime User Input using Console Class (Part-3).
- Basic Java – 18 || Difference between break and continue keywords.
- Basic Java – 19 || Sending Email using Java (Part-1).
- Basic Java – 20 || Sending Email with attachment using Java (Part-2).
- Basic Java – 21 || Stack memory and Heap memory in Java.
- Basic Java – 22 || Let’s learn more about String.
- Basic Java – 23 || String, StringBuffer & StringBuilder in Java.
- Basic Java – 24 || Exception Handling using Try Catch.
- File Handling | Reading data from word document(.doc or .docx) in JAVA.
- File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.
- File Handling | Writing data into an Excel(.XLSX or .XLS) File.
- File Handling | Implement formatting in Excel using Java.
- File Handling | Copy existing data from one workbook to another workbook in Java.
- File Handling | Reading data from PDF file using JAVA.
- File Handling || Traverse folders and subfolders in Java.
- File Handling || Reading and Writing data from a text file.
- File Handling || Multiple file creation using template based input data.
- Framework || Simple example of Key Driven Framework using excel sheet in Selenium(JAVA).
- QnA || How to use Constructors in Abstract class?
- QnA | Difference between Integer and int keywords.
- QnA | Can main method be overloaded?
- QnA | How do I reverse a String/Sentence in Java?
- QnA | Perform Multiplication and Division without * or / or % operators.
- QnA | How do I get the default value of data type?
- QnA | How to split String if it contains period symbol (.) in between?
- Different ways to Reverse a String in Java.
- Copy formatting & style of cells from one sheet to another.
- Getting IP address and Hostname using InetAddress Class.
- User inputs via Command Prompt using arguments of main() method of a class.
- Program for List and ArrayList in Java.
- Useful methods and implementation under Scanner Class.
- Swapping two variable values without using any third variable.
- Difference between int x= 10 and y=010 in Java.
- Parameterized Constructors v/s Setter and Getter function in JAVA.
- Override a Static Method.
More on next() and nextLine()
To get a better understanding and difference between next() and nextLine() methods let’s take another example. In the below example, we are taking inputs in the form of the arrays and will observe the behavior just making the difference between next() and nextLine().
public static void inputNext() { Scanner sc=new Scanner(System.in); System.out.print("Enter array lenght:"); int number=sc.nextInt(); String[] temp=new String[number]; System.out.println("Start Typing: "); for(int i=0;i<number;i++) { temp[i]=sc.next(); } System.out.println("Output:"); for (String string : temp) { System.out.println(string); } } Input: Suppose we want array of five, so number=5 C Java DotNet Python Ruby Eclipse HTML (We have give input more than 5 strings with whitespace) Output: (It will take only first 5 strings) C Java DotNet Python Ruby
public static void inputNextLine() { Scanner sc=new Scanner(System.in); System.out.print("Enter array lenght:"); int number=sc.nextInt(); Scanner sc1=new Scanner(System.in); String[] temp=new String[number]; System.out.println("Start Typing: "); for(int i=0;i<number;i++) { temp[i]=sc1.nextLine(); } System.out.println("Output:"); for (String string : temp) { System.out.println(string); } } Input: Suppose we want array of five, so number=5 Enter array lenght:5 Start Typing: User Input Line1 User Input Line2 User Input Line3 User Input Line4 User Input Line5 Output: User Input Line1 User Input Line2 User Input Line3 User Input Line4 User Input Line5
Note: If you noticed, we have used two objects of Scanner class sc and sc1, If we are not taking new Scanner object and use the same object sc in both the places, Last line of user input would be removed from the array. This happens because after giving input for the array length user would press enter to move further and this Enter would be the input for nextLine() for same Scanner object sc. |
next(Pattern)
Sometimes we need to perform some validation on the user input at runtime. We could apply the same rules using regular expression via Pattern Class. Suppose we want that user could be able to give inputs only in the form of alphabets, alphanumeric or valid email id etc.
In the below examples we have described different types of patterns or regular expression to get the accurate input from the end user at runtime.
public static void inputPattern() { Scanner sc=new Scanner(System.in); System.out.print("Pattern 1: only letters:>"); // Only allows letters in the range a-z String emailID=sc.next(Pattern.compile("[a-z]*")); System.out.println(emailID); Scanner sc1=new Scanner(System.in); System.out.print("Pattern 2: only letters ends with @:>"); // Only allows letters start with the range a-z and ends with @. emailID=sc1.next(Pattern.compile("[a-z]*@")); System.out.println(emailID); Scanner sc2=new Scanner(System.in); System.out.print("Pattern 3: letters@letters.com :>"); // Allows a valid email id in *@*.com format and only letters. emailID=sc2.next(Pattern.compile("[a-z]*@[a-z]*.com")); System.out.println(emailID); Scanner sc3=new Scanner(System.in); System.out.print("Pattern 4: letters_numbers@letters.com :>"); // Allows a valid email id in *@*.com format and only letters. emailID=sc3.next(Pattern.compile("[a-z,0-9]*@[a-z]*.com")); System.out.println(emailID); } Output: Pattern 1: only letters:>sample sample Pattern 2: only letters ends with @:>sample@ sample@ Pattern 3: letters@letters.com :>sample@allinoneblogs.com sample@allinoneblogs.com Pattern 4: letters_numbers@letters.com :>sample123@allinoneblogs.com sample123@allinoneblogs.com
hasNext() and hasNextLine()
Sometimes we need to take input from any external files like notepad, word etc. In that case, we cannot predict the actual word count or line number in the file. To avoid any runtime exception we could use hasNext() and hasNextLine() methods.
In the below examples, one method will count the total word and another method will count the total line numbers given in any file.
public static void hasNextExample() throws FileNotFoundException { Scanner sc1=new Scanner(new File("src\\UserInput.java")); int wordCount=0; while(sc1.hasNext()) { System.out.println(sc1.next()); wordCount++; } System.out.println("Total Words: "+wordCount); } public static void hasNextLineExample() throws FileNotFoundException { Scanner sc1=new Scanner(new File("src\\UserInput.java")); int lineCount=0; while(sc1.hasNextLine()) { System.out.println(sc1.nextLine()); lineCount++; } System.out.println("Total Lines: "+lineCount); }