Home Java Java-get-example Input From Console
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Input From Console

Advertisement
The Console Class inherits from Java.io.console and implements flushable interface. The Input from Console is used to access the character -based console device associated with the current Java virtual machine.

Input From Console

     

The Console Class inherits from Java.io.console and implements flushable interface. The Input from Console is used to access the character -based console device associated with the current Java virtual machine.

In this Tutorial we want to describe you a code that helps you in understanding a code Input from Console. For this we have a class 'Input From Console'. Inside the main method we have -

1)System.console ( )  - This method return you an console object and provides you unique console object ,that is associated with the current Java virtual machine.

The conditional operator if is used to evaluate, Incase the if operator is equal to null, The System.println print the "no console found" and exit from the system, Otherwise the println print the first and second number.

2)System.exit ( ) -  This method return you to exit from command prompt.l

3)console.readline ( ) - This method return the string var num1 and num2 and provides you to Reads a single line of text from the console and further these two string variable are parsed to a integer value  using Integer.parseint(num) to

The System.out.println print the sum  of two integer and assign to a sum.

InputFromConsole.java
import java.io.*;

public class InputFromConsole {

  public static void main(String args[]) {

  Console console = System.console();

  if (console == null) {

  System.err.println("No console found");
  System.exit(0);
  }
  
  System.out.println("1st num : ");
  String num1=console.readLine();  
  
  System.out.println("2nd num : ");
  
  String num2=console.readLine();
  
  System.out.println("Sum : "+(Integer.parseInt(num1)+Integer.parseInt(num2)));
  }
}

Output
1st num : 12
2nd num : 12
Sum : 24

Download code
Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 6, 2008

Ask Questions?    Discuss: Input From Console  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com