Java User Input


Java User Input: To pass data to a running Java program many ways exists like through

1. Command-line arguments
2. Keyboard input
3. GUI

Here 2nd style is chosen to illustrate as it is easy to write to a Learner but in realtime the 3rd one is used.

In Java User Input Mangoes name, rate and number are taken and their cost is evaluated.
import java.util.Scanner;                       ss // importing only one Scanner class
public class KeyboardInput
{
 public static void main(String args[])
 {
   Scanner scan1 = new Scanner(System.in);       // create Scanner object

   System.out.println("\nEnter Name of Mangoes:");     // start taking required inputs
   String mangoName = scan1.nextLine();

   System.out.println("Enter Mango cost:");
   double mangoCost = scan1.nextDouble();

   System.out.println("Enter Number of Mangoes:");
   int mangoNumber = scan1.nextInt();
                                                 // display the results of computation
   System.out.println("\nMango Name:" + mangoName);
   System.out.println("Each Mango cost Rs." + mangoCost + " and number of Mangoes: " + mangoNumber);
   System.out.println("Total Cost Rs." + mangoCost*mangoNumber);
 }
}

Java User InputOutput Screenshot on Java User Input

Scanner scan1 = new Scanner(System.in);

System.in gets connected automatically to underlying keyboard reading mechanism of OS. This is passed to Scanner constructor to link with. When linked, the Scanner object scan1 reads from Java User Input. Methods used are nextLine(), nextDouble() and nextInt() returning a string, a double value and a int value that can be used in coding for arithmetic manipulations.

For more command on keyboard input, read the three styles using different classes and different I/O Streams.

1. Using DataInputStream (java.io)
2. Using BufferedReader (java.io)
3. Using Scanner