Java: Проверьте, является ли строка числом
В этом уроке мы рассмотрим примеры того, как проверить, представляет ли строка число в Java. Мы будем использовать основную Java и библиотеку Apache Commons, а также регулярные выражения.
- Автор записи
Вступление
Строки-это удобный способ передачи информации и получения входных данных от пользователя.
В этой статье мы рассмотрим несколько способов проверить, является ли строка числовой в Java – то есть, представляет ли строка числовое значение.
Проверьте, является ли строка числовой с помощью ядра Java
Пользователи, как правило, довольно часто вводят неверные входные значения, поэтому разработчикам приходится как можно больше держать их за руку во время операций ввода-вывода.
Самый простой способ проверить, является ли строка числовой или нет,-это использовать один из следующих встроенных методов Java:
- Целое число.Синтаксический анализ()
- Целое число.valueOf()
- Double.Парседубль()
- Поплавок.парсеФлоат()
- Длинный.парсеЛонг()
Эти методы преобразуют заданную строку в ее числовой эквивалент. Если они не могут преобразовать его, создается исключение NumberFormatException , указывающее, что строка не была числовой.
Стоит отметить , что Integer.valueOf() возвращает новое целое число () , в то время как Integer.parseInt() возвращает примитив int . Имейте это в виду, если такая разница изменит ход вашей программы.
Давайте попробуем это:
Теперь мы можем абстрагировать эту функциональность в вспомогательный метод для удобства:
Теперь мы можем просто позвонить:
Выполнение этого кода приведет к:
С другой стороны, если мы ожидаем, что Строка будет содержать действительно большое число, то мы можем вызвать конструктор BigInteger(Строка) , который преобразует представление String в BigInteger .
Проверьте, является ли строка числовой с помощью Apache Commons
Apache Commons является одной из наиболее часто используемых сторонних библиотек для расширения базовой платформы Java. Это дает нам более точный контроль над основными классами Java, в данном случае строками.
Мы рассмотрим два класса из библиотеки Apache Commons:
- Количество элементов
- СтрингУтилы
Оба из которых очень похожи на их аналоги ванильного класса Java, но с акцентом на безопасные для нуля операции (для чисел и строк соответственно), что означает, что мы даже можем определить значения по умолчанию для отсутствующих ( нулевых ) значений.
Давайте теперь посмотрим, как мы можем проверить числовые значения с помощью этих методов.
числа.Сопоставимо()
Этот метод принимает строку и проверяет, является ли это анализируемым числом или нет, мы можем использовать этот метод вместо того, чтобы перехватывать исключение при вызове одного из методов, о которых мы упоминали ранее.
Это очень хорошо, потому что решений, связанных с частой обработкой исключений, следует по возможности избегать – именно в этом нам помогает этот метод.
Обратите внимание, что шестнадцатеричные числа и научные обозначения не считаются поддающимися анализу.
Теперь нам даже не нужен вспомогательный метод для удобства, так как поддается анализу() возвращает логическое значение само по себе:
Git Essentials
Ознакомьтесь с этим практическим руководством по изучению Git, содержащим лучшие практики и принятые в отрасли стандарты. Прекратите гуглить команды Git и на самом деле изучите это!
Этот код должен возвращать:
NumberUtils.isCreatable()
Этот метод также принимает строку и проверяет, является ли она допустимым номером Java . С помощью этого метода мы можем охватить еще больше чисел, потому что допустимое число Java включает в себя четные шестнадцатеричные и восьмеричные числа, научную нотацию, а также числа, отмеченные классификатором типа.
Теперь мы можем даже использовать что-то вроде:
числа.isDigits()
Число .Метод isDigits() проверяет, содержит ли строка только Цифры в Юникоде. Если Строка содержит начальный знак или десятичную точку, метод вернет false :
StringUtils.IsNumeric()
StringUtils.IsNumeric() является StringUtils эквивалентом NumberUtils.isDigits() .
Если Строка проходит числовой тест, она все равно может вызвать исключение NumberFormatException при анализе методами, о которых мы упоминали ранее, например, если она находится вне диапазона для int или long .
Используя этот метод, мы можем определить, можем ли мы проанализировать Строку в Целое число :
StringUtils.isNumericSpace()
Кроме того, если мы ожидаем найти больше чисел в строке, мы можем использовать isNumericSpace , еще один полезный StringUtils метод, о котором стоит упомянуть. Он проверяет, содержит ли строка | только цифры Юникода или пробелы .
Давайте проверим строку, содержащую числа и пробелы:
Проверьте, является ли строка числовой с помощью регулярного выражения
Несмотря на то, что большинство разработчиков будут довольны использованием уже реализованного метода, иногда у вас может быть очень специфическая проверка шаблонов:
И тогда мы можем вызвать этот метод:
Выполнение этого дает нам следующий результат:
Вывод
В этой статье мы рассмотрели несколько способов проверить, является ли строка числовой или нет (представляет собой число) в Java.
Мы начали использовать ядро Java и поймали исключение NumberFormatException , после чего мы использовали библиотеку Apache Commons. Оттуда мы использовали классы StringUtils и NumberUtils , чтобы проверить, является ли строка числовой или нет, в различных форматах.
Как проверить целое ли число java
In addition, this class provides several methods for converting an int to a String and a String to an int , as well as other constants and methods useful when dealing with an int .
Implementation note: The implementations of the «bit twiddling» methods (such as highestOneBit and numberOfTrailingZeros ) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).
Field Summary
| Modifier and Type | Field and Description |
|---|---|
| static int | BYTES |
Constructor Summary
Method Summary
| Modifier and Type | Method and Description |
|---|---|
| static int | bitCount (int i) |
Methods inherited from class java.lang.Object
Field Detail
MIN_VALUE
MAX_VALUE
BYTES
Constructor Detail
Integer
Integer
Method Detail
toString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
If the first argument is negative, the first element of the result is the ASCII minus character ‘-‘ ( ‘\u002D’ ). If the first argument is not negative, no sign character appears in the result.
The remaining characters of the result represent the magnitude of the first argument. If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character. The following ASCII characters are used as digits:
toUnsignedString
If the radix is smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX , then the radix 10 is used instead.
Note that since the first argument is treated as an unsigned value, no leading sign character is printed.
If the magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the magnitude will not be the zero character.
The behavior of radixes and the characters used as digits are the same as toString .
toHexString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 16) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as hexadecimal digits:
toOctalString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in octal (base 8) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 8) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The following characters are used as octal digits:
toBinaryString
The unsigned integer value is the argument plus 2 32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0 s.
The value of the argument can be recovered from the returned string s by calling Integer.parseUnsignedInt(s, 2) .
If the unsigned magnitude is zero, it is represented by a single zero character ‘0’ ( ‘\u0030’ ); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters ‘0’ ( ‘\u0030’ ) and ‘1’ ( ‘\u0031’ ) are used as binary digits.
toString
toUnsignedString
parseInt
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign ‘-‘ ( ‘\u002D’ ) or plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is not a value of type int .
parseInt
parseUnsignedInt
- The first argument is null or is a string of length zero.
- The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX .
- Any character of the string is not a digit of the specified radix, except that the first character may be a plus sign ‘+’ ( ‘\u002B’ ) provided that the string is longer than length 1.
- The value represented by the string is larger than the largest unsigned int , 2 32 -1.
parseUnsignedInt
valueOf
In other words, this method returns an Integer object equal to the value of:
valueOf
In other words, this method returns an Integer object equal to the value of:
valueOf
byteValue
shortValue
intValue
longValue
floatValue
doubleValue
toString
hashCode
hashCode
equals
getInteger
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.
If there is no property with the specified name, if the specified name is empty or null , or if the property does not have the correct numeric format, then null is returned.
In other words, this method returns an Integer object equal to the value of:
getInteger
The first argument is treated as the name of a system property. System properties are accessible through the System.getProperty(java.lang.String) method. The string value of this property is then interpreted as an integer value using the grammar supported by decode and an Integer object representing this value is returned.
The second argument is the default value. An Integer object that represents the value of the second argument is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .
In other words, this method returns an Integer object equal to the value of:
getInteger
- If the property value begins with the two ASCII characters 0x or the ASCII character # , not followed by a minus sign, then the rest of it is parsed as a hexadecimal integer exactly as by the method valueOf(java.lang.String, int) with radix 16.
- If the property value begins with the ASCII character 0 followed by another character, it is parsed as an octal integer exactly as by the method valueOf(java.lang.String, int) with radix 8.
- Otherwise, the property value is parsed as a decimal integer exactly as by the method valueOf(java.lang.String, int) with radix 10.
The second argument is the default value. The default value is returned if there is no property of the specified name, if the property does not have the correct numeric format, or if the specified name is empty or null .
decode
The sequence of characters following an optional sign and/or radix specifier (» 0x «, » 0X «, » # «, or leading zero) is parsed as by the Integer.parseInt method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign. No whitespace characters are permitted in the String .
compareTo
compare
compareUnsigned
toUnsignedLong
divideUnsigned
Note that in two’s complement arithmetic, the three other basic arithmetic operations of add, subtract, and multiply are bit-wise identical if the two operands are regarded as both being signed or both being unsigned. Therefore separate addUnsigned , etc. methods are not provided.
remainderUnsigned
highestOneBit
lowestOneBit
numberOfLeadingZeros
- floor(log2(x)) = 31 — numberOfLeadingZeros(x)
- ceil(log2(x)) = 32 — numberOfLeadingZeros(x — 1)
numberOfTrailingZeros
bitCount
rotateLeft
Note that left rotation with a negative distance is equivalent to right rotation: rotateLeft(val, -distance) == rotateRight(val, distance) . Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative: rotateLeft(val, distance) == rotateLeft(val, distance & 0x1F) .
rotateRight
Note that right rotation with a negative distance is equivalent to left rotation: rotateRight(val, -distance) == rotateLeft(val, distance) . Note also that rotation by any multiple of 32 is a no-op, so all but the last five bits of the rotation distance can be ignored, even if the distance is negative: rotateRight(val, distance) == rotateRight(val, distance & 0x1F) .
Проверка числа, целое или нет
Возможно ли через оператор «if» определить целое ли число и выполнить соответствующее действие, если оно целое?
Лучше использовать IntStream
// Проверка от обратного (true — это число не целое, false — число целое):
![]()
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Проверка, является ли число целым числом в Java
Есть ли какой-либо метод или быстрый способ проверить, является ли число целым числом (принадлежит полю Z) в Java?
Я думал, может быть, вычесть его из округленного числа, но я не нашел никакого метода, который мне в этом поможет.
Где я должен проверить? Целое API?
Ответы (11)
Быстро и грязно.
редактировать: это предполагает, что x уже находится в какой-то другой числовой форме. Если вы имеете дело со строками, загляните в Integer.parseInt .
Еще один пример 🙂
В этом примере можно использовать ceil и получить точно такой же эффект.
если вы говорите о значениях с плавающей запятой, вы должны быть очень осторожны из-за характера формата.
лучший известный мне способ сделать это — выбрать значение эпсилон, скажем, 0,000001f, а затем сделать что-то вроде этого:
по сути, вы проверяете, имеют ли z и целочисленный случай z одинаковую величину в пределах некоторого допуска. Это необходимо, потому что плавающие по своей сути неточны.