Character getnumericvalue java что это
Перейти к содержимому

Character getnumericvalue java что это

  • автор:

Character. Get Numeric Value Метод

Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.

Перегрузки

int Возвращает значение, которое представляет указанный символ Юникода.

int Возвращает значение, которое представляет указанный символ (кодовая точка Юникода).

GetNumericValue(Char)

int Возвращает значение, которое представляет указанный символ Юникода.

[Android.Runtime.Register("getNumericValue", "(C)I", "")] public static int GetNumericValue (char ch);
[] static member GetNumericValue : char -> int
Параметры

символ, который требуется преобразовать.

Возвращаемое значение

числовое значение символа в виде нерицательного int значения; значение -2, если символ имеет числовое значение, но значение не может быть представлено как неизбирательное int значение; значение -1, если символ не имеет числового значения.

Комментарии

int Возвращает значение, которое представляет указанный символ Юникода. Например, символ ‘\u005Cu216C’ (римская цифра пятьдесят) возвращает значение int со значением 50.

Буквы A–Z в верхнем регистре ( ‘\u005Cu0041’ до ‘\u005Cu005A’ ), строчные ( ‘\u005Cu0061’ до ‘\u005Cu007A’ ) и полноширинный вариант ( ‘\u005CuFF21’ до ‘\u005CuFF3A’ и ‘\u005CuFF41’ через ‘\u005CuFF5A’ ) имеют числовые значения от 10 до 35. Это не зависит от спецификации Юникода, которая не назначает числовые значения этим char значениям.

Если символ не имеет числового значения, возвращается значение -1. Если символ имеет числовое значение, которое не может быть представлено как неотрицательное целое число (например, дробное значение), возвращается значение -2.

Примечание. Этот метод не может обрабатывать дополнительные символы. Для поддержки всех символов Юникода, включая дополнительные символы, используйте #getNumericValue(int) метод .

Добавлено в версии 1.1.

Части этой страницы являются изменениями, основанными на работе, созданной и совместно используемой проектом Android и используемой в соответствии с условиями, Creative Commons 2.5 Attribution License.

Char. Get Numeric Value Method

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.

Converts a specified numeric Unicode character to a double-precision floating-point number.

Overloads

Converts the specified numeric Unicode character to a double-precision floating point number.

Converts the numeric Unicode character at the specified position in a specified string to a double-precision floating point number.

GetNumericValue(Char)

Converts the specified numeric Unicode character to a double-precision floating point number.

public: static double GetNumericValue(char c);
public static double GetNumericValue (char c);
static member GetNumericValue : char -> double
Public Shared Function GetNumericValue (c As Char) As Double
Parameters

The Unicode character to convert.

Returns

The numeric value of c if that character represents a number; otherwise, -1.0.

Examples

The following example demonstrates GetNumericValue.

using namespace System; int main() < String^ str = "input: 1"; Console::WriteLine( Char::GetNumericValue( '8' ) ); // Output: "8" Console::WriteLine( Char::GetNumericValue( str, 7 ) ); // Output: "1" >
using System; public class GetNumericValueSample < public static void Main() < string str = "input: 1"; Console.WriteLine(Char.GetNumericValue('8')); // Output: "8" Console.WriteLine(Char.GetNumericValue(str, 7)); // Output: "1" >> 
open System let str = "input: 1" printfn $"" // Output: "8" printfn $"" // Output: "1" 
Module GetNumericValueSample Sub Main() Dim str As String str = "input: 1" Console.WriteLine(Char.GetNumericValue("8"c)) ' Output: "8" Console.WriteLine(Char.GetNumericValue(str, 7)) ' Output: "1" End Sub End Module 

Remarks

The c parameter must be the Char representation of a numeric value. For example, if c is «5», the return value is 5. However, if c is «z», the return value is -1.0.

A character has an associated numeric value if and only if it is a member of one of the following UnicodeCategory categories: DecimalDigitNumber , LetterNumber , or OtherNumber .

The GetNumericValue method assumes that c corresponds to a single linguistic character and checks whether that character can be converted to a decimal digit. However, some numbers in the Unicode standard are represented by two Char objects that form a surrogate pair. For example, the Aegean numbering system consists of code points U+10107 through U+10133. The following example uses the ConvertFromUtf32 method to instantiate a string that represents AEGEAN NUMBER ONE. As the output from the example shows, the GetNumericValue(Char) method returns -1 if it is passed either a high surrogate or a low surrogate of this character.

int utf32 = 0x10107; // AEGEAN NUMBER ONE string surrogate = Char.ConvertFromUtf32(utf32); foreach (var ch in surrogate) Console.WriteLine("U+: ", Convert.ToUInt16(ch), Char.GetNumericValue(ch)); // The example displays the following output: // U+D800: -1 // U+DD07: -1 
let utf32 = 0x10107 // AEGEAN NUMBER ONE let surrogate = Char.ConvertFromUtf32 utf32 for ch in surrogate do printfn $"U+: " // The example displays the following output: // U+D800: -1 // U+DD07: -1 
Dim utf32 As Integer = &h10107 ' AEGEAN NUMBER ONE Dim surrogate As String = Char.ConvertFromUtf32(utf32) For Each ch In surrogate Console.WriteLine("U+: ", Convert.ToUInt16(ch), Char.GetNumericValue(ch)) Next ' The example displays the following output: ' U+D800: -1 ' U+DD07: -1 

See also

Applies to

GetNumericValue(String, Int32)

Converts the numeric Unicode character at the specified position in a specified string to a double-precision floating point number.

public: static double GetNumericValue(System::String ^ s, int index);
public static double GetNumericValue (string s, int index);
static member GetNumericValue : string * int -> double
Public Shared Function GetNumericValue (s As String, index As Integer) As Double
Parameters

The character position in s .

Returns

The numeric value of the character at position index in s if that character represents a number; otherwise, -1.

Exceptions

index is less than zero or greater than the last position in s .

Examples

The following code example demonstrates GetNumericValue.

using namespace System; int main() < String^ str = "input: 1"; Console::WriteLine( Char::GetNumericValue( '8' ) ); // Output: "8" Console::WriteLine( Char::GetNumericValue( str, 7 ) ); // Output: "1" >
using System; public class GetNumericValueSample < public static void Main() < string str = "input: 1"; Console.WriteLine(Char.GetNumericValue('8')); // Output: "8" Console.WriteLine(Char.GetNumericValue(str, 7)); // Output: "1" >> 
open System let str = "input: 1" printfn $"" // Output: "8" printfn $"" // Output: "1" 
Module GetNumericValueSample Sub Main() Dim str As String str = "input: 1" Console.WriteLine(Char.GetNumericValue("8"c)) ' Output: "8" Console.WriteLine(Char.GetNumericValue(str, 7)) ' Output: "1" End Sub End Module 

Remarks

The s parameter must be the string representation of a numeric value. For example, if the character at position index in s is «5», the return value is 5. However, if the character at position index in s is «z», the return value is -1.

Character positions in a string are indexed starting from zero.

A character has an associated numeric value if and only if it is a member of one of the following UnicodeCategory categories: DecimalDigitNumber , LetterNumber , or OtherNumber .

If the Char object at position index is the first character of a valid surrogate pair, the GetNumericValue(String, Int32) method determines whether the surrogate pair forms a numeric digit. For example, the Aegean numbering system consists of code points U+10107 through U+10133. The following example uses the ConvertFromUtf32 method to instantiate a string that represents each Aegean number. As the output from the example shows, the GetNumericValue(String, Int32) method returns the correct numeric value if it is passed the high surrogate of an Aegean number. However, if it is passed the low surrogate, it considers only the low surrogate in isolation and returns -1.

// Define a UTF32 value for each character in the // Aegean numbering system. for (int utf32 = 0x10107; utf32 at position : ", Convert.ToUInt16(surrogate[ctr]), ctr, Char.GetNumericValue(surrogate, ctr)); Console.WriteLine(); > // The example displays the following output: // U+D800 at position 0: 1 U+DD07 at position 1: -1 // U+D800 at position 0: 2 U+DD08 at position 1: -1 // U+D800 at position 0: 3 U+DD09 at position 1: -1 // U+D800 at position 0: 4 U+DD0A at position 1: -1 // U+D800 at position 0: 5 U+DD0B at position 1: -1 // U+D800 at position 0: 6 U+DD0C at position 1: -1 // U+D800 at position 0: 7 U+DD0D at position 1: -1 // U+D800 at position 0: 8 U+DD0E at position 1: -1 // U+D800 at position 0: 9 U+DD0F at position 1: -1 // U+D800 at position 0: 10 U+DD10 at position 1: -1 // U+D800 at position 0: 20 U+DD11 at position 1: -1 // U+D800 at position 0: 30 U+DD12 at position 1: -1 // U+D800 at position 0: 40 U+DD13 at position 1: -1 // U+D800 at position 0: 50 U+DD14 at position 1: -1 // U+D800 at position 0: 60 U+DD15 at position 1: -1 // U+D800 at position 0: 70 U+DD16 at position 1: -1 // U+D800 at position 0: 80 U+DD17 at position 1: -1 // U+D800 at position 0: 90 U+DD18 at position 1: -1 // U+D800 at position 0: 100 U+DD19 at position 1: -1 // U+D800 at position 0: 200 U+DD1A at position 1: -1 // U+D800 at position 0: 300 U+DD1B at position 1: -1 // U+D800 at position 0: 400 U+DD1C at position 1: -1 // U+D800 at position 0: 500 U+DD1D at position 1: -1 // U+D800 at position 0: 600 U+DD1E at position 1: -1 // U+D800 at position 0: 700 U+DD1F at position 1: -1 // U+D800 at position 0: 800 U+DD20 at position 1: -1 // U+D800 at position 0: 900 U+DD21 at position 1: -1 // U+D800 at position 0: 1000 U+DD22 at position 1: -1 // U+D800 at position 0: 2000 U+DD23 at position 1: -1 // U+D800 at position 0: 3000 U+DD24 at position 1: -1 // U+D800 at position 0: 4000 U+DD25 at position 1: -1 // U+D800 at position 0: 5000 U+DD26 at position 1: -1 // U+D800 at position 0: 6000 U+DD27 at position 1: -1 // U+D800 at position 0: 7000 U+DD28 at position 1: -1 // U+D800 at position 0: 8000 U+DD29 at position 1: -1 // U+D800 at position 0: 9000 U+DD2A at position 1: -1 // U+D800 at position 0: 10000 U+DD2B at position 1: -1 // U+D800 at position 0: 20000 U+DD2C at position 1: -1 // U+D800 at position 0: 30000 U+DD2D at position 1: -1 // U+D800 at position 0: 40000 U+DD2E at position 1: -1 // U+D800 at position 0: 50000 U+DD2F at position 1: -1 // U+D800 at position 0: 60000 U+DD30 at position 1: -1 // U+D800 at position 0: 70000 U+DD31 at position 1: -1 // U+D800 at position 0: 80000 U+DD32 at position 1: -1 // U+D800 at position 0: 90000 U+DD33 at position 1: -1 
// Define a UTF32 value for each character in the // Aegean numbering system. for utf32 in 0x10107..0x10133 do let surrogate = Char.ConvertFromUtf32 utf32 for i = 0 to surrogate.Length - 1 do printf $"U+ at position : " printfn "" // The example displays the following output: // U+D800 at position 0: 1 U+DD07 at position 1: -1 // U+D800 at position 0: 2 U+DD08 at position 1: -1 // U+D800 at position 0: 3 U+DD09 at position 1: -1 // U+D800 at position 0: 4 U+DD0A at position 1: -1 // U+D800 at position 0: 5 U+DD0B at position 1: -1 // U+D800 at position 0: 6 U+DD0C at position 1: -1 // U+D800 at position 0: 7 U+DD0D at position 1: -1 // U+D800 at position 0: 8 U+DD0E at position 1: -1 // U+D800 at position 0: 9 U+DD0F at position 1: -1 // U+D800 at position 0: 10 U+DD10 at position 1: -1 // U+D800 at position 0: 20 U+DD11 at position 1: -1 // U+D800 at position 0: 30 U+DD12 at position 1: -1 // U+D800 at position 0: 40 U+DD13 at position 1: -1 // U+D800 at position 0: 50 U+DD14 at position 1: -1 // U+D800 at position 0: 60 U+DD15 at position 1: -1 // U+D800 at position 0: 70 U+DD16 at position 1: -1 // U+D800 at position 0: 80 U+DD17 at position 1: -1 // U+D800 at position 0: 90 U+DD18 at position 1: -1 // U+D800 at position 0: 100 U+DD19 at position 1: -1 // U+D800 at position 0: 200 U+DD1A at position 1: -1 // U+D800 at position 0: 300 U+DD1B at position 1: -1 // U+D800 at position 0: 400 U+DD1C at position 1: -1 // U+D800 at position 0: 500 U+DD1D at position 1: -1 // U+D800 at position 0: 600 U+DD1E at position 1: -1 // U+D800 at position 0: 700 U+DD1F at position 1: -1 // U+D800 at position 0: 800 U+DD20 at position 1: -1 // U+D800 at position 0: 900 U+DD21 at position 1: -1 // U+D800 at position 0: 1000 U+DD22 at position 1: -1 // U+D800 at position 0: 2000 U+DD23 at position 1: -1 // U+D800 at position 0: 3000 U+DD24 at position 1: -1 // U+D800 at position 0: 4000 U+DD25 at position 1: -1 // U+D800 at position 0: 5000 U+DD26 at position 1: -1 // U+D800 at position 0: 6000 U+DD27 at position 1: -1 // U+D800 at position 0: 7000 U+DD28 at position 1: -1 // U+D800 at position 0: 8000 U+DD29 at position 1: -1 // U+D800 at position 0: 9000 U+DD2A at position 1: -1 // U+D800 at position 0: 10000 U+DD2B at position 1: -1 // U+D800 at position 0: 20000 U+DD2C at position 1: -1 // U+D800 at position 0: 30000 U+DD2D at position 1: -1 // U+D800 at position 0: 40000 U+DD2E at position 1: -1 // U+D800 at position 0: 50000 U+DD2F at position 1: -1 // U+D800 at position 0: 60000 U+DD30 at position 1: -1 // U+D800 at position 0: 70000 U+DD31 at position 1: -1 // U+D800 at position 0: 80000 U+DD32 at position 1: -1 // U+D800 at position 0: 90000 U+DD33 at position 1: -1 
' Define a UTF32 value for each character in the ' Aegean numbering system. For utf32 As Integer = &h10107 To &h10133 Dim surrogate As String = Char.ConvertFromUtf32(utf32) For ctr As Integer = 0 To surrogate.Length - 1 Console.Write("U+ at position : ", Convert.ToUInt16(surrogate(ctr)), ctr, Char.GetNumericValue(surrogate, ctr)) Next Console.WriteLine() Next ' The example displays the following output: ' U+D800 at position 0: 1 U+DD07 at position 1: -1 ' U+D800 at position 0: 2 U+DD08 at position 1: -1 ' U+D800 at position 0: 3 U+DD09 at position 1: -1 ' U+D800 at position 0: 4 U+DD0A at position 1: -1 ' U+D800 at position 0: 5 U+DD0B at position 1: -1 ' U+D800 at position 0: 6 U+DD0C at position 1: -1 ' U+D800 at position 0: 7 U+DD0D at position 1: -1 ' U+D800 at position 0: 8 U+DD0E at position 1: -1 ' U+D800 at position 0: 9 U+DD0F at position 1: -1 ' U+D800 at position 0: 10 U+DD10 at position 1: -1 ' U+D800 at position 0: 20 U+DD11 at position 1: -1 ' U+D800 at position 0: 30 U+DD12 at position 1: -1 ' U+D800 at position 0: 40 U+DD13 at position 1: -1 ' U+D800 at position 0: 50 U+DD14 at position 1: -1 ' U+D800 at position 0: 60 U+DD15 at position 1: -1 ' U+D800 at position 0: 70 U+DD16 at position 1: -1 ' U+D800 at position 0: 80 U+DD17 at position 1: -1 ' U+D800 at position 0: 90 U+DD18 at position 1: -1 ' U+D800 at position 0: 100 U+DD19 at position 1: -1 ' U+D800 at position 0: 200 U+DD1A at position 1: -1 ' U+D800 at position 0: 300 U+DD1B at position 1: -1 ' U+D800 at position 0: 400 U+DD1C at position 1: -1 ' U+D800 at position 0: 500 U+DD1D at position 1: -1 ' U+D800 at position 0: 600 U+DD1E at position 1: -1 ' U+D800 at position 0: 700 U+DD1F at position 1: -1 ' U+D800 at position 0: 800 U+DD20 at position 1: -1 ' U+D800 at position 0: 900 U+DD21 at position 1: -1 ' U+D800 at position 0: 1000 U+DD22 at position 1: -1 ' U+D800 at position 0: 2000 U+DD23 at position 1: -1 ' U+D800 at position 0: 3000 U+DD24 at position 1: -1 ' U+D800 at position 0: 4000 U+DD25 at position 1: -1 ' U+D800 at position 0: 5000 U+DD26 at position 1: -1 ' U+D800 at position 0: 6000 U+DD27 at position 1: -1 ' U+D800 at position 0: 7000 U+DD28 at position 1: -1 ' U+D800 at position 0: 8000 U+DD29 at position 1: -1 ' U+D800 at position 0: 9000 U+DD2A at position 1: -1 ' U+D800 at position 0: 10000 U+DD2B at position 1: -1 ' U+D800 at position 0: 20000 U+DD2C at position 1: -1 ' U+D800 at position 0: 30000 U+DD2D at position 1: -1 ' U+D800 at position 0: 40000 U+DD2E at position 1: -1 ' U+D800 at position 0: 50000 U+DD2F at position 1: -1 ' U+D800 at position 0: 60000 U+DD30 at position 1: -1 ' U+D800 at position 0: 70000 U+DD31 at position 1: -1 ' U+D800 at position 0: 80000 U+DD32 at position 1: -1 ' U+D800 at position 0: 90000 U+DD33 at position 1: -1 

Откуда берётся 49?

5c55751f52bbf708897892.png

Вот от сюда int var = n[j];
если вы хотите продолжить свои странные действия, делайте так
int var = Character.getNumericValue(n[j]);

Ответ написан более трёх лет назад

Нравится 1 1 комментарий

web_Developer_Victor

hellcaster @web_Developer_Victor Автор вопроса

Я понимаю, что выглядит странно. Это школьная олимпиада. Программа, которая подсчитывает сколько цифр в промежутке между 1 и N

Программа возвращает код символа а не сам символ

Всем привет! Метод sumDigitsInNumber должен возвращать сумму цифр полученного числа (546), но вместо этого возвращает сумму кодов чисел из таблицы ASCII(возвращает 159, сумма кодов 53 + 52 + 54), изучаю Java меньше недели и никак не могу понять в чем проблема, пытался гуглить, но ничего не нагуглил. Помогите пожалуйста) P.S. столкнулся с проблемой не только в этой программе, для себя написал программу «угадай число» и там при вводе числа с клавиатуры через BufferedReader тоже возвращался код символа( Заранее всем спасибо!)

public class Solution < public static void main(String[] args) < System.out.println(sumDigitsInNumber(546)); >public static int sumDigitsInNumber(int number) < String s = Integer.toString(number); char[] chars = s.toCharArray(); number = 0; for (int i = 0; i < chars.length; i++) < number += (int) chars[i]; >return number; > > 

Отслеживать
8,049 5 5 золотых знаков 33 33 серебряных знака 52 52 бронзовых знака
задан 31 окт 2018 в 10:37
13 2 2 бронзовых знака

3 ответа 3

Сортировка: Сброс на вариант по умолчанию

Делал буквально на днях, но двумя другими способами. Здесь используются мои имена пакетов.

Основной класс SumOfDigits.java:

package info.sjd; import java.util.logging.Logger; import info.sjd.service.SumOfDigitsService; public class SumOfDigits < private static Logger logger = Logger.getLogger(SumOfDigits.class.getName()); public static void main(String[] args) < int number = 12345; int sumOfDigitsByIntegerDivision = SumOfDigitsService.sumOfDigitsByIntegerDivision(number); int sumOfDigitsByCharSplitting = SumOfDigitsService.sumOfDigitsByCharSplitting(number); logger.info("The sum of digits of number " + number + " by integer division is " + sumOfDigitsByIntegerDivision); logger.info("The sum of digits of number " + number + " by character splitting is " + sumOfDigitsByCharSplitting); >> 

Сервисный класс SumOfDigitsService.java:

package info.sjd.service; public class SumOfDigitsService < public static int sumOfDigitsByIntegerDivision(int number) < int sumOfDigits = 0; while (number >0) < sumOfDigits = sumOfDigits + (number % 10); number = number / 10; >return sumOfDigits; > public static int sumOfDigitsByCharSplitting(int number) < int sumOfDigits = 0; String stringNumber = String.valueOf(number); for (int i = 0; i < String.valueOf(number).length(); i++) < sumOfDigits = sumOfDigits + Integer.parseInt(String.valueOf(stringNumber.charAt(i))); >return sumOfDigits; > > 

В вашем случае скорее всего нужно будет разобраться с приведением типов и возможно использовать переопределение метода .toString().

Да, с приведением типов разберитесь. Все работает, если так: package info.sjd;

public class Solution < public static void main(String[] args) < System.out.println(sumDigitsInNumber(546)); >public static int sumDigitsInNumber(int number) < String s = Integer.toString(number); char[] chars = s.toCharArray(); number = 0; for (int i = 0; i < chars.length; i++) < number += Integer.parseInt(String.valueOf(chars[i])); >return number; > > 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *