Java system in read example

How can we read from standard input in Java?

The standard input(stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings. To read any data from a keyboard, we can use either a Reader class or Scanner class.

Example1

import java.io.*; public class ReadDataFromInput < public static void main (String[] args) < int firstNum, secondNum, result; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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

Example2

import java.util.*; public class ReadDataFromScanner < public static void main (String[] args) < int firstNum, secondNum, result; Scanner scanner = new Scanner(System.in); 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

Источник

Read Input from System.in in Java

Read Input from System.in in Java

  1. Read Input by Using System.in in Java
  2. Read Input Using the System.in and BufferedReader Class in Java
  3. Read Input Using the System.console() Method in Java

This tutorial introduces how to read user input from the console using the System.in in Java.

Java provides a low-level stream class System to read user input, which uses an input stream to read input. The System is a class in Java that helps to perform system-related tasks.

We can pass this to the Scanner class, and then by using its methods; we can get user input of several types such as String , int , float , etc. Let’s understand by some examples.

Read Input by Using System.in in Java

Using the System.in in a Java code is easy; pass the class in the Scanner constructor and use the nextLine() method. This method reads and returns a string.

import java.util.Scanner;  public class SimpleTesting  public static void main(String[] args)   Scanner sc = new Scanner(System.in);  System.out.println("Enter a value :");  String str = sc.nextLine();  System.out.println("User input: "+str);   > > 
Enter a value : 2 User input: 2 

Read Input Using the System.in and BufferedReader Class in Java

This is another solution to read user input where we used the BufferedReader class rather than the Scanner class. This code does the same task, and we used the readLine() method here to read the data.

This method belongs to the BufferedReader class and returns a string. See the example below.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;  public class SimpleTesting  public static void main(String[] args) throws IOException   System.out.println("Enter a value :");  BufferedReader br = new BufferedReader(  new InputStreamReader( System.in ));  String str = br.readLine();  System.out.println(str);   > > 

Read Input Using the System.console() Method in Java

Java System class provides a console() method to deal with console-related tasks. So, to read data, we can use this method also.

This method returns a console object by which we can call the readLine() method to read data. See the example below.

import java.io.Console; import java.io.IOException;  public class SimpleTesting  public static void main(String[] args) throws IOException   Console c = System.console();  System.out.println("Enter a value : ");  String str = c.readLine();  System.out.println(str);  > > 

The Java Scanner class is commonly used to read user data and provides methods for each data type.

We can use these methods to read specific data. Some of them are below.

public int nextInt(); // reads integer input  public float nextFloat(); // reads decimal input  public String nextLine(); // reads string input 

In the example below, we used these methods to read a different type of user input in Java. It will help you to understand the Java console.

import java.io.IOException; import java.util.Scanner;  public class SimpleTesting  public static void main(String[] args) throws IOException   Scanner sc = new Scanner(System.in);  System.out.println("Enter a string value : ");  String str = sc.nextLine();  System.out.println(str);  System.out.println("Enter an int value : ");  int a = sc.nextInt();  System.out.println(a);  System.out.println("Enter a float value : ");  float f = sc.nextFloat();  System.out.println(f);  > > 
Enter a string value : string string Enter an int value : 23 23 Enter a float value : 34 34.0 

Related Article — Java Input

Источник

Java system in read example

  • The basics of TOGAF certification and some ways to prepare TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.
  • Haskell vs. PureScript: The difference is complexity Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .
  • A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
  • Postman API platform will use Akita to tame rogue endpoints Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .
  • How to make use of specification-based test techniques Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .
  • GitHub Copilot Chat aims to replace Googling for devs GitHub’s public beta of Copilot Chat rolls out GPT-4 integration that embeds a chat assistant into Visual Studio, but concerns .
  • Navigate multi-cloud billing challenges Keeping track of cloud bills from multiple clouds or accounts can be complex. Learn how to identify multi-cloud billing .
  • 5 Google Cloud cost optimization best practices Cost is always a top priority for enterprises. For those considering Google Cloud, or current users, discover these optimization .
  • How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
  • BrightTALK @ Black Hat USA 2022 BrightTALK’s virtual experience at Black Hat 2022 included live-streamed conversations with experts and researchers about the .
  • The latest from Black Hat USA 2023 Use this guide to Black Hat USA 2023 to keep up on breaking news and trending topics and to read expert insights on one of the .
  • API keys: Weaknesses and security best practices API keys are not a replacement for API security. They only offer a first step in authentication — and they require additional .
  • AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
  • Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
  • Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .

Источник

Ввод данных с клавиатуры

В Java используются два основных способа ввода данных с клавиатуры:

  • С помощью метода readLine() объекта, порожденного от класса BufferdReader из пакета java.io.
  • С помощью nextLine() и других методов объекта, созданного от класса Scanner из пакета java.util.

Однако в обоих случаях изначально используется System.in – объект класса InputStream, присвоенный переменной in, находящейся в классе System пакета java.lang. Данный объект выполняет функцию стандартного потока ввода, т. е. ввода с клавиатуры. (В то время как System.out – стандартный поток вывода.)

В Java объект System.in обеспечивает низкоуровневый ввод, при котором методом read() считываются байты. Например, если ввести «ab» и нажать Enter, будет прочитано три байта. В десятичном представлении значение первого байта будет соответствовать символу «a» по таблице символов, второго – символу «b», третьего – символу перехода на новую строку.

Если же ввести букву национального алфавита, которая не может кодироваться одним байтом, то каждый ее составляющий байт будет прочитан по отдельности.

Для преобразования байтов в символы, а затем в строки полученное от System.in передают в конструкторы классов-оберток. Обертки используют функционал переданного им объекта, но дополняют его своим.

Первая обертка – класс InputStreamReader, который преобразует набор байтов в символ. Класс BufferedReader буферизует ввод, обеспечивая считывание из потока ввода (клавиатура это или файл – не важно) целых строк, что делает процесс более быстрым.

import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; public class Buffered { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); String title = reader.readLine(); String pagesStr = reader.readLine(); int pages = Integer.parseInt(pagesStr); System.out.println(title); System.out.println(pages+1); } }

Выражение BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); есть сокращенная запись от:

InputStream a = System.in; InputStreamReader b = new InputStreamReader(a); BufferedReader reader = new BufferedReader(b);

В случае Scanner дело обстоит попроще, так как класс может больше:

import java.util.Scanner; public class Scan  public static void main(String[] args)  Scanner scanner = new Scanner(System.in); String title = scanner.nextLine(); int pages = scanner.nextInt(); System.out.println(title); System.out.println(pages + 1); > >

У сканера есть методы, проверяющие тип вводимых данных (hasNextInt() и т. п.). Несмотря на удобство Scanner, если надо просто считывать строки без их анализа, предпочитают использовать BufferedReader, так как он работает быстрее. В остальном выбор зависит от специфики задачи.

Программирование на Java. Курс

Источник

Чтение из консоли

В этой статье мы разберёмся, как считывать информацию из консоли Консоль – это стандартный поток ввода-вывода. Чтобы читать данные из консоли, мы воспользуемся двумя разными классами из стандартной библиотеки Java.

Способ 1: Чтение из консоли с помощью System.in.read

Простейший способ чтения данных из консоли – это метод System.in.read(). Данный метод позволяет считывать данные по одному коду. Это блокирующий метод, то есть, вызвав его, выполнение программы продолжится только тогда, когда будет введён какой-либо символ в консоль:

int code = System.in.read(); char c = (char) code; System.out.println("Вы ввели: " + c + ", код символа: " + code);

Это очень простой способ чтения из консоли и есть более удобные способы чтения.

Способ 2: Чтение из консоли с помощью Scanner

Класс java.util.Scanner предоставляет несколько удобных методов для чтения из консоли:

  • hasNextInt() – вернёт true, если из консоли сейчас возможно вычитать целое число
  • nextInt() – вычитает целое число из консоли
  • hasNextDouble() – вернёт true, если из консоли сейчас возможно вычитать число типа double
  • nextDouble() – вычитает вещественное число из консоли
  • hasNextLine() – вернёт true, если из консоли возможно считать какие-либо символы
  • nextLine() – вычитывает строку из консоли

Все эти методы являются блокирующими.

В данном примере мы проверяем, доступно ли в консоли целое число и если да, то снова выводим его в консоль:

Scanner scanner = new Scanner(System.in); System.out.print(«Введите целое число: «); if (scanner.hasNextInt()) < int i = scanner.nextInt(); System.out.println(i); >else

Аналогично используются методы hasNextDouble()/nextDouble() для вещественных чисел и методы hasNextLine()/nextLine() для строк.

Заключение

В данной статье мы разобрались, как вычитывать данные из стандартного потока вывода. Теперь вы знаете, как вычитать из консоли числа, символы и строки.

Исходный код

import java.io.IOException; public class ReadFromConsoleIn < public static void main(String[] args) throws IOException < int code = System.in.read(); char c = (char) code; System.out.println("Вы ввели: " + c + ", код символа: " + code); >>
public class ReadFromConsoleScanner < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.print("Введите целое число: "); if (scanner.hasNextInt()) < int i = scanner.nextInt(); System.out.println(i); >else < System.out.println("Вы ввели не целое число"); >> >

Источник

Читайте также:  Creating dynamic web pages with php
Оцените статью