Home  >  Article  >  Java  >  In Java, how do we read data from standard input?

In Java, how do we read data from standard input?

PHPz
PHPzforward
2023-09-03 22:45:071550browse

In Java, how do we read data from standard input?

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.

Example 1

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);
      }
   }
}

Output

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);
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete