To get user input at runtime we have to use Scanner Class. It contains various inbuilt methods which can be used to make user interaction more smoother and error free.
Scanner Class
Please visit below link to get theoretical as well as practical knowledge of Scanner Class and its methods:
Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).
In this post, we have combined all these methods and tried to describe the same using different functions.
Note: Please do comment all section in the code except that one for which you are looking. For any help or assistance do write us in comments at the end of the page or Contact Us. |
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.regex.Pattern; /** * */ /** * @author ashok.kumar * */ public class UserInput { /** * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { //Sample of Printing table of user defined number table(); inputInteger(); // Takes input only in Integer format. inputDouble(); // Takes input in integer and decimal format. inputBoolean(); // Takes input only in TRUE and FALSE strings. //Sample of taking USER Input via next() method. Scanner sc=new Scanner(System.in); System.out.print("Enter String value(s) seperated by spaces: "); String itemName=sc.next(); System.out.println(itemName); //Sample of taking USER Input via nextLine() method. Scanner sc1=new Scanner(System.in); System.out.print("Enter String values in form of sentence: "); String storeAddress=sc1.nextLine(); System.out.println(storeAddress); // Using next() with ARRAYS. inputNext(); // Using nextLine() with ARRAYS. inputNextLine(); // User REGULAR Expression to Avoid UNWANTED DATA from end user at runtime. inputPattern(); // Reding external file and extracting WORD COUNT. hasNextExample(); // Reding external file and extracting LINE COUNT. hasNextLineExample(); } 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); } 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); } } 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); } } public static void inputPattern() { Scanner sc=new Scanner(System.in); System.out.print("Pattern 1: only letters:>"); String emailID=sc.next(Pattern.compile("[a-z]*")); // Only allows letters in the range a-z System.out.println(emailID); Scanner sc1=new Scanner(System.in); System.out.print("Pattern 2: only letters ends with @:>"); emailID=sc1.next(Pattern.compile("[a-z]*@")); // Only allows letters start with the range a-z and ends with @. System.out.println(emailID); Scanner sc2=new Scanner(System.in); System.out.print("Pattern 3: letters@letters.com :>"); emailID=sc2.next(Pattern.compile("[a-z]*@[a-z]*.com")); // Allows a valid email id in *@*.com format and only letters. System.out.println(emailID); Scanner sc3=new Scanner(System.in); System.out.print("Pattern 4: letters_numbers@letters.com :>"); emailID=sc3.next(Pattern.compile("[a-z,0-9]*@[a-z]*.com")); // Allows a valid email id in *@*.com format and only letters. System.out.println(emailID); } 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); } public static void table() { Scanner sc=new Scanner(System.in); System.out.print("Enter any number: "); int userInput=sc.nextInt(); System.out.println("Table of "+userInput); for(int i=1;i<=10;i++) { System.out.println(userInput*i); } } }
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.