Taking Input from Keyboard

From our earlier section, we know that we can pass input parameter by passing the arguments. What we will do if we need to provide the taking Input from Keyboard dynamically? Let’s discuss briefly how to take input from keyboard in java. This section will help programmer to understand the foundation of the java program on the handling the input.

Objective:

  • How to take input from Keyboard
  • Command line argument
  • readLine() Method
  • Scanner class
  • Examples

How to take input from Keyboard?

We have understood from the last section that if we want to pass some input to the function, we need to pass through parameter / argument.

Demo d = new Demo();
d.takeInput(10,12);
d.takeInput(39,10);

What we will do when we want to work on taking Input from Keyboard dynamically. This is the crucial part of java. In Java we can take input from keyboard in 3 ways.

  • Through command line
  • By readLine() Method
  • By Scanner class
Taking Input from Keyboard

Let’s understand each ways in detail.

Through Command Line:

We are using Command line for compiling and running the java code. To compile the java code we need to run the below command.

javac <filename.java>

This will create the .class file which will be used to runt the java code. To run we need to use below command.

Java <filename>

In java, any code starts the execution with main() method. Without main() method Java program execution will not start.

public static void main(String args[])

Here in the above statement, args[] is the array of String which stores the string argument from the command line. During the execution of java program, we can pass this command line argument with java code run command.

Java <filename> <argument>

Let’s us understand this with a simple example.

Example:

//File Name: DemoCommand.java
class DemoCommand{
	public static void main(String args[]){
		System.out.println(args[0])
	}
}

Compile the above java program with below command.

Javac DemoCommand.java

The command line argument need to be provided, during the execution phase as below. This should be String type as we have String args[] in the main() method signature.

Java DemoCommand Hello

Form the above command you can notice that we have passed the “Hello” String in command line execution. As we have passed only one string it will take as 0th argument for main() method. As args[] is an array, it will take the argument from command line with index and index will start from 0 and will continue with 1,2,3,4 and so on.

What will happen if we want to pass the multiple argument in single command? Can we do that?

Yes. Of course we can do this. We just need to pass multiple argument with comma separated.

  Java DemoCommand Hello TestingLpoint

As the array index will starts from 0 and continue with 1,2,3,4 and so on, if we will pass the index 1 in args[] array as array[1] it will print only TestingLPoint for the above command. Here we need to remember that whatever input we pass from the command line; it will take as String. If you want to take some int or float or any other except string input from command line, you need to use separate method in code to convert this to corresponding type from string.

Let’s understand how to pass integer value from command line argument for taking Input from Keyboard.

int intarg;
if (args.length > 0) {
    try {
        intarg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Integer Argument" + args[0] + " must be an integer.");
        System.exit(1);
    }
}

From the above example you can notice that we have used parseInt() method to convert from String to Integer value. As parseInt() will throw an Exception named NumberFormatException we have defined the try catch block to handle NumberFormatException Exception. We will understand more about the Exception and try—catch block later. But for now you can remember that to handle any type of exception we need to handle the Exception class with try—-catch block.

readLine() Method:

This is not the inbuilt method available in java. This method is available in java.io package. So we need to import this package before using readLine() method.

Syntax:

Public String readLine() throws IOException{
------------
------------
}

readLine() method will throw an Exception called IOException. To handle this IOException, we need to mention throws with the method signature. This readLine() is present in BufferedReader and InputStreamReader class. And both these classed are available inside the java.io package.

The return type of this method is String as you can notice in the method signature. Let’s understand this with a simple example.

Example:

import java.io.*;
class Inputwithreadline{
	public static void main(String args[]) throws IOException{
		InputStreamReader is = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(is);
		System.out.println("Enter the Input from Keyboard: ");
		String inpt = br.readLine();
		System.out.println("You have entered: "+ inpt);
		}
}

Output:

Enter the Input from Keyboard:
pratik
You have entered: Pratik

Explanation

From the above example, you can notice that we have used 2 classes. One is InputStreamReader and other is BufferedReader. First we have created the object reference of InputStreamReader and then will pass this object to BufferedReader object instance. After that we have used the readLine() method which help to take input from Keyboard.

Here System.in is in the Keyboard and InputStreamReader behaves like a channel connected to it.readLine() method takes the input from keyboard and stores in the String format.

Let’s discuss about the Scanner class in java.

Scanner class:

Scanner class has lots of benefits over the readLine() method. It can accept all types of input from keyboard including, Numeric, String and other types. It actually reads the formatted input and converts it into binary form.

In Java, Scanner class is present inside the java.util package. It is the easiest way to handle the input from Keyboard.

We need to remember some points when we will work on the scanner class.

  • We need to pass the predefined object system.in when we will create the object of Scanner class. System. In is nothing but represented as Standard Input Stream. If we want to take input from file, then we can pass the object of corresponding class file.
  • When we will ready data of Int from keyboard, we need to use nextInt() method. Like int we can user nextFloat(), nextShort() etc to read float, short data type respectively.
  • But to read String data type we need to use nextLine(). Line will considered for Strinf datatype.

We are having some constructor for Scanner class which is used to take input from Keyboard.

Constructor:

FileReader fr = new FileReader(“filename.txt”)

Scanner s1 = new Scanner(fr)

Scanner s2 = new Scanner(System.in)

String s = “TestingLpoint”

Scanner s3 = new Scanner(s)

We are having many methods which will help us to handle the input from keyboard and file while using the Scanner class. Let’s understand about each one of the method.

MethodDescription
boolean hasNext()Return “TRUE” if a token of any type is available for read
boolean hasNextByte()Return “TRUE” if a Byte value is available for read
boolean hasNextShort()Return “TRUE” if a Short value is available for read
boolean hasNextInt()Return “TRUE” if a Int value is available for read
boolean hasNextFloat()Return “TRUE” if a Float value is available for read
boolean hasNextLong ()Return “TRUE” if a Long value is available for read
boolean hasNextDouble()Return “TRUE” if a Double value is available for read
boolean hasNextLine()Return “TRUE” if a Line is available for read
String next()Return the next token of any type from the input source
boolean nextBoolean()Return the next token as boolean value
byte nextByte()Return the next token as short value
short nextShort()Return the next token as byte value
int  nextInt()Return the next token as int value
long nextLong()Return the next token as long value
double nextDouble()Return the next token as double value
String nextLineReturn the next line of the input as String

Let’s understand with an Example.

To work with Scanner class for taking Input from Keyboard dynamically, we need to remember some points as below

  • It is determined if a specific type of input is availability by calling one of Scanner’s hasNext() method.
  • If input is available, it is to be calling one of the Scanner’s next() method
  • The Process is to be repeated until the input is exhausted.

Example:

import java.util.*;
class Try{
	public static void main(String args[]){
		Scanner sc= new Scanner(System.in);
		System.out.println("Enter a Number from Keyboard: ");
		int i = sc.nextInt();
		System.out.println("Output is: "+ i);
	}
}

Output:

Enter a Number from Keyboard:
34
Output is: 34

Explanation:

Here you can see that we have created the object for Scanner class. As Scanner is not the part of core, we have to import this before use. System.in is referring to take the input from the Keyboard command line. nextInt is checking the available next integer in command line. As it found 34, it returns 34 and assign to the variable i.

What if we will give a String or character in the output instead of giving integer value?

Yes , you are correct. It will throw an Error.

Let see with Example.

import java.util.*;
class Try{
	public static void main(String args[]){
		Scanner sc= new Scanner(System.in);
		System.out.println("Enter a Number from Keyboard: ");
		int i = sc.nextInt();
		System.out.println("Output is: "+ i);
	}
}

Output:

Like this other methods will be implemented to byte, short, String, double, float data type.

Summary:

  • There are 3 ways for taking Input from Keyboard dynamically.
  • args[] in main method is the array of String which stores the string argument from the command line.
  • An array index will starts from 0 and continue with 1,2,3,4 and so on.
  • As parseInt() will throw an Exception named NumberFormatException we need to define the try catch block to handle NumberFormatException Exception.
  • readLine() method is not the inbuilt method available in java. This method is available in java.io package. So we need to import this package before using readLine() method.
  • System.in is in the Keyboard and InputStreamReader behaves like a channel connected to it.readLine() method takes the input from keyboard and stores in the String format.
  • We need to pass the predefined object system.in when we will create the object of Scanner class. System. In is nothing but represented as Standard Input Stream. If we want to take input from file, then we can pass the object of corresponding class file.
  • When we will ready data of Int from keyboard, we need to use nextInt() method. Like int we can user nextFloat(), nextShort() etc to read float, short data type respectively.
  • But to read String data type we need to use nextLine(). Line will considered for Strinf datatype.

if we will give a String or character in the output instead of giving integer value for nextInt() method, then it will throw an Error.

Leave a Reply

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