Monday, January 12, 2009

How to accept inputs from user while running java program

There are different waysm through which we can pass input value while java program is running.In the below example, i have used java.util.Scanner class for the same.

One of the main reason for using Scanner class is, it actually allows user to pass primitive data types such as integers etc.

Here you dont have to pass the argument while call the java class file, here user will be asked to enter input when actually inputs are required.

I am explaining  in terms of layman point of view so that it will be easier to understand.

Here is the code:
JavaScanner.java
--------------------
import java.util.Scanner;

/*
Author: Anaparthi Subrahmanyam
Published: 01-13-2009
*/
public class  JavaScanner
{
  public static void main(String[] args) 
  {
    Scanner scanner = new Scanner(System.in);
    try
    {
      System.out.println("Value 1");
      int int1 = scanner.nextInt();
      System.out.println("Value 2");
      int int2 = scanner.nextInt();
      System.out.println("Sum");
      System.out.println("---------- Sum-------------");
      System.out.println(int1+int2);
      System.out.println("---------------------------"); 
    }
    catch (Exception e)
    {
      System.out.println("Error in input");
      e.printStackTrace();
    }
  }
}
--------------------



No comments:

Post a Comment