Home > Java > javaTutorial > body text

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

PHPz
Release: 2023-09-03 22:45:07
forward
1557 people have browsed it

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);
      }
   }
}
Copy after login

Output

Enter a first number:
15
Enter a second number:
20
The Result is: 300
Copy after login

##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);
   }
}
Copy after login

Output

Enter a first number:
20
Enter a second number:
25
The Result is: 500
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template