Basic Java – 15 || Runtime User Input using Scanner Class (Part-1).

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.

UserInputProcess
UserInputProcess



Scanner Class

  1. It can be used via java.util.Scanner library files.
  2. There is a major role of Whitespace and Enter while taking user inputs using Scanner class.
  3. These user inputs can be stored in any variable for future use.
  4. Most commonly methods are nextInt(), nextDouble(), nextBoolean(), next(), nextLine(), next(Pattern), hasNext(), hasNextLine() etc. from Scanner Class.

Note: Execution of program would be blocked until the user does not give any input.

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:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:


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);	
	}



1603total visits,5visits today

Leave a Reply

Your email address will not be published. Required fields are marked *