Standard input (stdin) can be represented by System.in in Java. System.in is an instance of the InputStream class. This means that all its methods work on bytes, not strings. To read any data from keyboard we can use Reader class or Scanner class.
import java.io.*; public class ReadDataFromInput { public static void main (String[] args) { int firstNum, secondNum, result; <strong> BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); </strong> try { System.out.println("Enter a first number:"); firstNum = Integer.parseInt(br.readLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(br.readLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); } catch (IOException ioe) { System.out.println(ioe); } } }
Enter a first number: 15 Enter a second number: 20 The Result is: 300
##Example 2
import java.util.*; public class ReadDataFromScanner { public static void main (String[] args) { int firstNum, secondNum, result; <strong> Scanner scanner = new Scanner(System.in); </strong> System.out.println("Enter a first number:"); firstNum = Integer.parseInt(scanner.nextLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(scanner.nextLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); } }
Enter a first number: 20 Enter a second number: 25 The Result is: 500
The above is the detailed content of In Java, how do we read data from standard input?. For more information, please follow other related articles on the PHP Chinese website!