java util inputmismatchexception что это

Чтение ввода с консоли

Ключевой момент: чтение ввода с консоли даёт возможность программе принимать ввод от пользователя

В предыдущем параграфе значение radius было зафиксировано в исходном коде. Чтобы использовать другой радиус, нужно каждый раз менять исходный код и перекомпилировать программу. Очевидно, что это не удобно, поэтому вместо такого подхода, вы можете использовать класс Scanner для консольного ввода.

Java использует System.out для обращения к стандартному устройству вывода и System.in для стандартного устройства ввода. По умолчанию, устройство вывода – это дисплей монитора, а устройство ввода – это клавиатура. Для выполнения консольного вывода, вы просто используете метод println для отображения в консоль простых значений или строк. Консольный ввод не поддерживается напрямую в Java, но вы можете использовать класс Scanner для создания объекта для чтения ввода из System.in. Это делается так:

Синтаксис new Scanner(System.in) создаёт объект типа Scanner. Синтаксис Scanner input объявляет, что input является переменной, чей тип – Scanner. Вся строка Scanner input = new Scanner(System.in) создаёт объект Scanner и присваивает его ссылку переменной input. Объект может вызывать свои методы. Вызвать метод объекта означает запросить объект выполнить задачу. Вы можете вызвать метод nextDouble() для чтения значения double следующим образом:

Инструкция считывает число с клавиатуры и присваивает это число переменной radius. Перепишем программу из предыдущего урока, чтобы она запрашивала радиус у пользователя:

Обратите внимание, что десятичным разделителем, в зависимости от локали вашей системы, может быть точка или запятая. Если у вас возникает ошибка InputMismatchException, то посмотрите чуть ниже.

Строка 10 отображает в консоли надпись «Введите радиус: ». Это называется prompt (подсказка, напоминание), поскольку он направляет пользователя к вводу данных. Если ваша программа ожидает ввода с клавиатуры, она всегда должна говорить пользователю, ввод каких данных от него ожидается.

print или println

Метод print на десятой строке

идентичен методу println с той лишь разницей, что println переходит к началу новой строки после отображения строки, а print после вывода не переходит к следующей строке.

Строка 8 создаёт объект Scanner. Инструкция на одиннадцатой строке считывает ввод с клавиатуры.

После того, как пользователь ввёл число и нажал клавишу Ввод (Enter), программа считывает число и присваивает его переменной radius.

Больше подробностей об объектах будет представлено в одной из последующих главах. На текущий момент просто примите, что это то, как получить вход с консоли.

Конкретный импорт

Класс Scanner находится в пакете java.util. Он импортируется на строке 2. Имеется два вида инструкций import: конкретный импорт и импорт с подстановочными символами. Конкретный импорт импортирует определённый единичный класс в инструкции import. Например, следующая инструкция импортирует Scanner из пакета java.util.

Импорт с подстановочным символом

Импорт с подстановочным символом импортирует все классы из пакета, используя звёздочку в качестве подстановочного символа. Например, следующая инструкция импортирует все классы из пакета java.util.

Читайте также:  какой конденсатор нужен для среднечастотного динамика

Разница в производительности между импортом одного класса или всех классов в пакете

Информация для классов из импортируемого пакета не считывается во время компиляции или во время выполнения если класс в программе не используется. Инструкция import просто говорит компьютеру, где расположен класс. Нет разницы в производительности между конкретным импортом или импортом с подстановочным символом.

Ещё одна программа, которая даёт пример чтения нескольких значений с клавиатуры. Программа считывает три числа и показывает их среднее арифметическое:

Листинг с номерами строк:

Код для импорта класса Scanner (строка 2) и создание объекта Scanner (строка 8) такие же, как и в предшествующем примере, как и во всех новых программах, которые вы будете писать, для чтения ввода с клавиатуры.

Строка 10 делает запрос пользователю ввести три числа. Числа считываются на строках 11-13. Вы можете ввести три числа разделив их пробелами, а затем нажать кнопку Enter, или нажимать клавишу Enter после каждого числа. Оба варианта показаны в примерах запуска этой программы.

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

Примечание: большинство программа в начальных главах этого сайта выполняют три шага – ввод, обработка и вывод, это также называется IPO (от английских input, process, and output). Ввод – это получение данных от пользователя; обработка – это выработка результата, используя ввод, а вывод – это отображение результатов.

Решение проблемы с ошибкой InputMismatchException

Если при попытке ввести число с плавающей точкой, например, такой строкой программы:

Вы получаете ошибку:

Это означает, что локаль* вашей системы в качестве десятичного разделителя ожидает не точку, а запятую (или наоборот).

*Региональный стандарт, региональные настройки (проф. жарг. лока́ль от англ. locale, /lɔ.kal/ или /ləuˈkɑ:l/) — набор параметров, определяющий региональные настройки пользовательского интерфейса, такие как язык, страна, часовой пояс, набор символов и т. п.

Выходов из этой ситуации два:

Для этого при создании объекта Scanner добавьте .useLocale(Locale.US). Например, объект создавался следующим образом:

После дополнения получается такая строка создания объекта:

Также в начале программы требуется сделать дополнительный импорт:

К примеру, код программы из этого параграфа, чтобы она начала принимать числа, у которых десятичным разделителем является точка, становится таким:

Источник

Java Hungry

Java developers tutorials and coding.

InputMismatchException in Java with Examples

In this tutorial, we will discuss the InputMismatchException in java. Also, we will answer whether InputMismatchException is a checked exception or unchecked exception. Before diving deep into the topic let us first understand when does InputMismatchException occur.

When does InputMismatchException occur?

InputMismatchException is thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

Читайте также:  что бы мы ни делали в этой жизни anacondaz текст

The java.util package provides a Scanner class to take input of primitive data types and strings. It is the simplest way to read user input in java. If the user does not provide the proper type of input or input is out of range, then InputMismatchException happens.

InputMismatchException is an Unchecked Exception

The java.util package provides InputMismatchException class that inherits NoSuchElementException class. NoSuchElementException inherits RuntimeException. So, InputMismatchException is a runtime exception. Hence, it is an unchecked exception.

This class has two constructors that are listed below.

Example of InputMismatchException

The InputMismatchException exception is produced only when the input type is not proper, for example, if java application expects long datatype as input but the user gives the float value as input it should generate InputMismatchException exception. Please find below the code example.

Output:
Enter Integer Value: 1.1
We have given input as float expecting integer java.util.InputMismatchException

In the above example, if the application is looking for integer value but we have provided a float value.

Case 2: Again if we provide an input that is not within integer range

Output:
Enter Integer Value: 12222222222222222
input is not with in integer range java.util.InputMismatchException

These examples are true for every datatype. If input data does not comply below two conditions, then InputMismatchException will generate.

1. Input data type not match.
2. Input data is not in the range of expected datatype.

In the above examples, we are exiting from the code when the exception generates.

How to avoid InputMismatchException

When we provide a valid input that will comply with the conditions described in the above section. Only correct input can avoid this kind of exception.

That’s all for today, please mention in comments in case you have any questions related to InputMismatchException in java.

Источник

Input Mismatch Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an InputMismatchException with null as its error message string.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an InputMismatchException with null as its error message string.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Читайте также:  какой кетчуп без сахара и крахмала

(Inherited from Throwable) Class (Inherited from Throwable) Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

Initializes the cause of this throwable to the specified value.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Sets the Handle property.

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

[Solved] Exception in thread “main” java.util.InputMismatchException

What causes java.util.InputMismatchException?

A Scanner throws this exception to indicate that the token retrieved does not match the expected type pattern, or that the token is out of range for the expected type.

In simpler terms, you will generally get this error when user input or file data do not match with expected type.

Let’s understand this with the help of simple example.

If you put NA as user input, you will get below exception.
Output:

As you can see, we are getting Exception in thread «main» java.util.InputMismatchException for input int because user input NA is String and does not match with expected input Integer.

Hierarchy of java.util.InputMismatchException

InputMismatchException extends NoSuchElementException which is used to denote that request element is not present.

Constructor of java.util.InputMismatchException

There are two constructors exist for java.util.InputMismatchException

How to solve java.util.InputMismatchException?

In order to fix this exception, you must verify the input data and you should fix it if you want application to proceed further correctly. This exception is generally caused due to bad data either in the file or user input.

Источник

Сказочный портал