System in java что это

от admin

System in java что это

Наиболее простой способ взаимодействия с пользователем представляет консоль: мы можем выводить на консоль некоторую информацию или, наоборот, считывать с консоли некоторые данные. Для взаимодействия с консолью в Java применяется класс System , а его функциональность собственно обеспечивает консольный ввод и вывод.

Вывод на консоль

Для создания потока вывода в класс System определен объект out . В этом объекте определен метод println , который позволяет вывести на консоль некоторое значение с последующим переводом курсора консоли на следующую строку. Например:

В метод println передается любое значение, как правило, строка, которое надо вывести на консоль. И в данном случае мы получим следующий вывод:

При необходимости можно и не переводить курсор на следующую строку. В этом случае можно использовать метод System.out.print() , который аналогичен println за тем исключением, что не осуществляет перевода на следующую строку.

Консольный вывод данной программы:

Но с помощью метода System.out.print также можно осуществить перевод каретки на следующую строку. Для этого надо использовать escape-последовательность \n:

Нередко необходимо подставлять в строку какие-нибудь данные. Например, у нас есть два числа, и мы хотим вывести их значения на экран. В этом случае мы можем, например, написать так:

Но в Java есть также функция для форматированного вывода, унаследованная от языка С: System.out.printf() . С ее помощью мы можем переписать предыдущий пример следующим образом:

В данном случае символы %d обозначают спецификатор, вместо которого подставляет один из аргументов. Спецификаторов и соответствующих им аргументов может быть множество. В данном случае у нас только два аргумента, поэтому вместо первого %d подставляет значение переменной x, а вместо второго — значение переменной y. Сама буква d означает, что данный спецификатор будет использоваться для вывода целочисленных значений.

Кроме спецификатора %d мы можем использовать еще ряд спецификаторов для других типов данных:

%x : для вывода шестнадцатеричных чисел

%f : для вывода чисел с плавающей точкой

%e : для вывода чисел в экспоненциальной форме, например, 1.3e+01

%c : для вывода одиночного символа

%s : для вывода строковых значений

При выводе чисел с плавающей точкой мы можем указать количество знаков после запятой, для этого используем спецификатор на %.2f , где .2 указывает, что после запятой будет два знака. В итоге мы получим следующий вывод:

Ввод с консоли

Для получения ввода с консоли в классе System определен объект in . Однако непосредственно через объект System.in не очень удобно работать, поэтому, как правило, используют класс Scanner , который, в свою очередь использует System.in . Например, напишем маленькую программу, которая осуществляет ввод чисел:

Так как класс Scanner находится в пакете java.util , то мы вначале его импортируем с помощью инструкции import java.util.Scanner .

Для создания самого объекта Scanner в его конструктор передается объект System.in . После этого мы можем получать вводимые значения. Например, в данном случае вначале выводим приглашение к вводу и затем получаем вводимое число в переменную num.

Чтобы получить введенное число, используется метод in.nextInt(); , который возвращает введенное с клавиатуры целочисленное значение.

Пример работы программы:

Класс Scanner имеет еще ряд методов, которые позволяют получить введенные пользователем значения:

next() : считывает введенную строку до первого пробела

nextLine() : считывает всю введенную строку

nextInt() : считывает введенное число int

nextDouble() : считывает введенное число double

nextBoolean() : считывает значение boolean

nextByte() : считывает введенное число byte

nextFloat() : считывает введенное число float

nextShort() : считывает введенное число short

То есть для ввода значений каждого примитивного типа в классе Scanner определен свой метод.

Например, создадим программу для ввода информации о человеке:

Здесь последовательно вводятся данные типов String, int, float и потом все введенные данные вместе выводятся на консоль. Пример работы программы:

Обратите внимание, что для ввода значения типа float (то же самое относится к типу double) применяется число «1,7», где разделителем является запятая, а не «1.7», где разделителем является точка. В данном случае все зависит от текущей языковой локализации системы. В моем случае русскоязычная локализация, соответственно вводить необходимо числа, где разделителем является запятая. То же самое касается многих других локализаций, например, немецкой, французской и т.д., где применяется запятая.

Class System

For simple stand-alone Java applications, a typical way to write a line of output data is:

See the println methods in class PrintStream .

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention, this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream, the value of the variable out , has been redirected to a file or other destination that is typically not continuously monitored. The encoding used in the conversion from characters to bytes is equivalent to Console.charset() if the Console exists, Charset.defaultCharset() otherwise.

Method Details

setIn

setOut

setErr

console

inheritedChannel

In addition to the network-oriented channels described in inheritedChannel , this method may return other kinds of channels in the future.

setSecurityManager

Otherwise, the argument is established as the current security manager. If the argument is null and no security manager has been established, then no action is taken and the method simply returns.

getSecurityManager

currentTimeMillis

See the description of the class Date for a discussion of slight discrepancies that may arise between «computer time» and coordinated universal time (UTC).

nanoTime

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) — no guarantees are made except that the resolution is at least as good as that of currentTimeMillis() .

Differences in successive calls that span greater than approximately 292 years (2 63 nanoseconds) will not correctly compute elapsed time due to numerical overflow.

The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.

For example, to measure how long some code takes to execute:

To compare elapsed time against a timeout, use instead of because of the possibility of numerical overflow.

arraycopy

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

If dest is null , then a NullPointerException is thrown.

If src is null , then a NullPointerException is thrown and the destination array is not modified.

  • The src argument refers to an object that is not an array.
  • The dest argument refers to an object that is not an array.
  • The src argument and dest argument refer to arrays whose component types are different primitive types.
  • The src argument refers to an array with a primitive component type and the dest argument refers to an array with a reference component type.
  • The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
  • The srcPos argument is negative.
  • The destPos argument is negative.
  • The length argument is negative.
  • srcPos+length is greater than src.length , the length of the source array.
  • destPos+length is greater than dest.length , the length of the destination array.

Otherwise, if any actual component of the source array from position srcPos through srcPos+length-1 cannot be converted to the component type of the destination array by assignment conversion, an ArrayStoreException is thrown. In this case, let k be the smallest nonnegative integer less than length such that src[srcPos+ k ] cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions srcPos through srcPos+ k -1 will already have been copied to destination array positions destPos through destPos+ k -1 and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)

identityHashCode

getProperties

The current set of system properties for use by the getProperty(String) method is returned as a Properties object. If there is no current set of system properties, a set of system properties is first created and initialized. This set of system properties includes a value for each of the following keys unless the description of the associated value indicates that the value is optional.

Shows property keys and associated values

Key Description of Associated Value
java.version Java Runtime Environment version, which may be interpreted as a Runtime.Version
java.version.date Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD format, which may be interpreted as a LocalDate
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.vendor.version Java vendor version (optional)
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version, whose value is the feature element of the runtime version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version which may be interpreted as a Runtime.Version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version, whose value is the feature element of the runtime version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path (refer to ClassLoader.getSystemClassLoader() for details)
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator («/» on UNIX)
path.separator Path separator («:» on UNIX)
line.separator Line separator («\n» on UNIX)
user.name User’s account name
user.home User’s home directory
user.dir User’s current working directory
native.encoding Character encoding name derived from the host environment and/or the user’s settings. Setting this system property has no effect.

Multiple paths in a system property value are separated by the path separator character of the platform.

Note that even if the security manager does not permit the getProperties operation, it may choose to permit the getProperty(String) operation.

lineSeparator

On UNIX systems, it returns «\n» ; on Microsoft Windows systems it returns «\r\n» .

setProperties

The argument becomes the current set of system properties for use by the getProperty(String) method. If the argument is null , then the current set of system properties is forgotten.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

getProperty

If there is no current set of system properties, a set of system properties is first created and initialized in the same manner as for the getProperties method.

setProperty

clearProperty

getenv

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.»+name) permission. This may result in a SecurityException being thrown. If no exception is thrown the value of the variable name is returned.

System properties and environment variables are both conceptually mappings between names and values. Both mechanisms can be used to pass user-defined information to a Java process. Environment variables have a more global effect, because they are visible to all descendants of the process which defines them, not just the immediate Java subprocess. They can have subtly different semantics, such as case insensitivity, on different operating systems. For these reasons, environment variables are more likely to have unintended side effects. It is best to use system properties where possible. Environment variables should be used when a global effect is desired, or when an external system interface requires an environment variable (such as PATH ).

On UNIX systems the alphabetic case of name is typically significant, while on Microsoft Windows systems it is typically not. For example, the expression System.getenv(«FOO»).equals(System.getenv(«foo»)) is likely to be true on Microsoft Windows.

getenv

If the system does not support environment variables, an empty map is returned.

The returned map will never contain null keys or values. Attempting to query the presence of a null key or value will throw a NullPointerException . Attempting to query the presence of a key or value which is not of type String will throw a ClassCastException .

The returned map and its collection views may not obey the general contract of the Object.equals(java.lang.Object) and Object.hashCode() methods.

The returned map is typically case-sensitive on all platforms.

If a security manager exists, its checkPermission method is called with a RuntimePermission(«getenv.*») permission. This may result in a SecurityException being thrown.

When passing information to a Java subprocess, system properties are generally preferred over environment variables.

What is system.in

Here Scanner is the CLASS. user_input is the OBJECT under Scanner class. What is ( System.in )? Is it a parameter passed or a object under Scanner class?.

Consider another example.

Here I have set dog class to accept size as a parameter.

What exactly is System.in ?

Mauren's user avatar

10 Answers 10

Scanner class accepts input stream as a parameter and System class have a static variable in which is of type InputStream . System.in gives you a instance of of type InputStream .

The «standard» input stream. This stream is already open and ready to supply input data.

Suresh Atta's user avatar

System.in is an InputStream which is typically connected to keyboard input of console programs. System.in is not used as often since data is commonly passed to a command line Java application via command line arguments, or configuration files. In applications with GUI the input to the application is given via the GUI. This is a separate input mechanism from Java IO.

System.in is the «standard» input stream.

ltalhouarne's user avatar

System.in — "in" is object of class InputStream which is defined as static variables in class "System" which is used to read data from the console. In short "System.in" gives you a instance of of type InputStream.

When we create a Scanner class object we need to pass "System.in" as parameter in Scanner class Constructor. So basically using "System.in" Scanner class becomes able to read the data from console and then using different methods which are provided by Scanner class (like nextInt(), nextLong(), next() etc.), we can get data in the form of our desired datatypes (like int, double, String etc.).

Scanner class has a constructor Scanner(InputStream) in its profile i.e when we call Scanner() constructor during the object creation time it will let you to pass the object of InputStream class.

«in» is an object of «InputStream» class defined in System class(like «out» is an object of PrintStream class defined in System class).

Вывод и ввод данных в консоль Java

Консоль (console) в Java обеспечивает простое и удобное взаимодействия с пользователем. С помощью консоли можно выводить какую-нибудь информацию либо, напротив, используя консоль, считывать данные. В этой статье будет рассказано о том, как осуществляется ввод и вывод данных в консоли Java.

Чтобы обеспечивать взаимодействие с консолью, в языке программирования Java используют класс System.

Вывод на консоль в Java

Чтобы создать потока вывода в вышеупомянутый класс System, вам понадобится специальный объект out. В нём определен метод println, обеспечивающий вывод значения на консоль и перевод курсора консоли на другую строку.

Рассмотрим практический пример с Hello world:

Что здесь происходит? В метод println осуществляется передача значения (в нашем случае это строка), которое пользователь желает вывести в консоль Java. Консольный вывод данных в Джава будет следующий:

Выполнять перевод строки не обязательно. Если необходимость в этом отсутствует, применяют метод System.out.print() . Он аналогичен println, но перевод каретки на следующую строку не выполняется.

Вывод в консоли Java:

Однако никто не мешает, используя System.out.print, всё же выполнить перенос на следующую строку. Как вариант — использование \n:

Также есть возможность подставить в строку Ява данные, которые объявлены в переменных. Вот, как это реализуется:

В консоли увидим:

Ещё в Java существует функция, предназначенная для форматирования вывода в консоли, — System.out.printf() . При использовании со спецификаторами, она позволяет добиться нужного формата вывода.

Спецификаторы: • %d — для вывода в консоль целочисленных значений; • %x — для 16-ричных чисел; • %f — выводятся числа с плавающей точкой; • %e — для чисел в экспоненциальной форме (1.3e+01); • %c — вывод в консоль одиночного символа; • %s — вывод в консоль строковых значений.

Рассмотрим, как это функционирует на практике:

Когда осуществляется вывод в консоль Java значений с плавающей точкой, есть возможность задать количество знаков после запятой. Спецификатор %.2f (точнее, «.2») определяет, что будет 2 знака после запятой. Вывод в консоль Java будет следующим:

Ввод с консоли Java или как ввести данные с консоли Джавы

Чтобы обеспечить ввод с консоли Java, в классе System есть объект in. Именно через объект System.in работать не очень удобно, поэтому часто применяют класс Scanner. Он уже, в свою очередь, как раз таки и применяет System.in.

Рассмотрим практический пример:

Сам по себе класс Scanner хранится в пакете java.util, поэтому в начале кода мы выполняем его импорт посредством команды import java.util.Scanner.

Для создания непосредственно объекта Scanner в его конструктор осуществляется передача объекта System.in. Далее можно получать значения. В нашей мини-программе сначала выводится просьба ввести номер, а потом введённое пользователем число помещается в переменную num (для получения введённого значения задействуется метод in.nextInt() , возвращающий набранное на клавиатуре целочисленное значение.

Лучше всего попробовать работу этой программы с помощью одного из многочисленных онлайн-компиляторов.

Работать она будет простейшим образом: 1. Сначала вы увидите сообщение в консоли «Введите любой номер:». 2. После ввода числа (пускай это будет 8) в консоли появится второе сообщение — «Ваш номер: 8».

Для класса Scanner предусмотрены и другие методы: • next() — для считывания введённой строки до первого пробела; • nextLine() — для всей введённой строки; • nextInt() — считывает введённое число int; • nextDouble() — для double; • nextBoolean() — для boolean; • nextByte() — для byte; • nextFloat() — для float; • nextShort() — для short.

Давайте напишем простую программу, обеспечивающую ввод информационных данных о человеке в консоль Java:

В этой программке пользователь последовательно вводит данные разных типов: String, int и float. Потом вся информация выводится в консоль Java:

Вот и всё. Это базовые вещи, если же вас интересуют более продвинутые знания, записывайтесь на курс OTUS в Москве:

Читать:
Install queued unity что делать

Похожие статьи