Java перевести число в символ

Java: преобразование строки в число и наоборот

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

Как преобразовать строку в число в Java?

Речь идёт о преобразовании String to Number. Обратите внимание, что в наших примерах, с которыми будем работать, задействована конструкция try-catch. Это нужно нам для обработки ошибки в том случае, когда строка содержит другие символы, кроме чисел либо число, которое выходит за рамки диапазона предельно допустимых значений указанного типа. К примеру, строку «onlyotus» нельзя перевести в тип int либо в другой числовой тип, т. к. при компиляции мы получим ошибку. Для этого нам и нужна конструкция try-catch.

Читайте также:  Javascript window href reload

Преобразуем строку в число Java: String to byte

Выполнить преобразование можно следующими способами:

C помощью конструктора:

try < Byte b1 = new Byte("10"); System.out.println(b1); >catch (NumberFormatException e)

С помощью метода valueOf класса Byte:

String str1 = «141»; try < Byte b2 = Byte.valueOf(str1); System.out.println(b2); >catch (NumberFormatException e)

С помощью метода parseByte класса Byte:

byte b = 0; String str2 = «108»; try < b = Byte.parseByte(str2); System.out.println(b); >catch (NumberFormatException e)

А теперь давайте посмотрим, как выглядит перевод строки в массив байтов и обратно в Java:

String str3 = «20150»; byte[] b3 = str3.getBytes(); System.out.println(b3); //массив байтов переводится обратно в строку try < String s = new String(b3, "cp1251"); System.out.println(s); >catch (UnsupportedEncodingException e)

Преобразуем строку в число в Java: String to int

Здесь, в принципе, всё почти то же самое:

Используем конструктор:

try < Integer i1 = new Integer("10948"); System.out.println(i1); >catch (NumberFormatException e)

Используем метод valueOf класса Integer:

String str1 = «1261»; try < Integer i2 = Integer.valueOf(str1); System.out.println(i2); >catch (NumberFormatException e)

Применяем метод parseInt:

int i3 = 0; String str2 = «203955»; try < i3 = Integer.parseInt(str2); System.out.println(i3); >catch (NumberFormatException e)

Аналогично действуем и для других примитивных числовых типов данных в Java: short, long, float, double, меняя соответствующим образом названия классов и методов.

Как преобразовать число в строку в Java?

Теперь поговорим о преобразовании числа в строку (Number to String). Рассмотрим несколько вариантов:

1. Преобразование int to String в Java:

 
int i = 53; String str = Integer.toString(i); System.out.println(str);

2. Преобразование double to String в Java:

 
double i = 31.6e10; String str = Double.toString(i); System.out.println(str);

3. Преобразуем long to String в Java:

 
long i = 3422222; String str = Long.toString(i); System.out.println(str);

4. Преобразуем float to String в Java:

 
float i = 3.98f; String str = Float.toString(i); System.out.println(str);

Источник

Преобразование между char и int в Java

В этом посте будет обсуждаться преобразование между char и int в Java.

1. Преобразование char в int

Чтобы преобразовать символ в целое число, вы можете использовать любой из следующих методов:

1. Неявное преобразование

Простое решение — воспользоваться преимуществом неявного преобразования компилятором, когда значение char присваивается целому числу, как показано ниже:

2. Использование String.getBytes() метод

Строка может быть преобразована в последовательность байтов с помощью getBytes() метод, который возвращает массив байтов. Чтобы сделать это для одного символа, используйте как:

3. Использование Character.digit() метод

Если вам нужно числовое значение, представленное символом в указанной системе счисления, вы можете использовать Character.digit() метод. Например,

2. Преобразование int в char

Чтобы преобразовать целое число в символ, вы можете использовать любой из следующих методов:

1. Использование кастинга

Если ваше целое число представляет диапазон символов ASCII, вы можете просто преобразовать его в символ без потери точности.

Чтобы получить соответствующее символьное представление указанной цифры, вы можете сделать следующее:

2. Использование Character.forDigit() метод

Стандартное решение для получения символьного представления для конкретной цифры в указанной системе счисления использует Character.forDigit() метод.

Чтобы преобразовать указанный символ (кодовая точка Unicode) в его представление UTF-16, вы можете использовать Character.toChars() метод, который возвращает массив символов.

Это все о преобразовании между char и int в Java.

Средний рейтинг 5 /5. Подсчет голосов: 7

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

int to char in java

Java Course - Mastering the Fundamentals

An integer can be converted into a character in Java using various methods. Some of these methods for converting int to char in Java are: using typecasting , using toString() method, using forDigit() method, and by adding ' 0 '. This article discusses all these methods to convert an integer data type into a character data type in Java.

Introduction

Sometimes you may need to convert an integer into a character in Java. There are various ways to get this int to char conversion in Java accomplished, and we will discuss the following ways in this article:

  • Using typecasting in Java.
  • Using toString() method in Java.
  • Using forDigit() method in Java.
  • By adding '0' .

In the upcoming sections, let us discuss these methods to convert int to char in Java.

Using Typecasting in Java

We can very easily convert int to char using typecasting in Java. Typecasting basically means converting a particular data type to some other data type.

The syntax for typecasting in Java is:

Here data_type1 is the data type of the variable var1 , and data_type2 is the data type to which var1 is converted by typecasting. This means that the value of var1 is converted to data_type2.

So, if we have an integer variable and we need to convert it into a character variable, we just need to typecast it by using ( c h a r ) (char) ( c h a r ) before assigning it a value.

Note: that the variable c c c will be assigned the character whose ASCII value is 98 . Hence, if you want a particular alphabet or symbol to be converted from integer to character , make sure the integer holds the value of that alphabet/symbol in ASCII code.

Example: Java Program to Convert int to char using typecasting

Let us take an example to convert a given integer into character in Java using typecasting as described above.

As shown in the output, the integer a is converted into a character using typecasting in Java and then stored in c .

The thing to note about this method is that the integer will not be converted into the character , but instead will get converted to the character for which the integer is the ASCII code. Hence, the code did not output 89 , but Y as ASCII code of Y is 89 .

Using toString() method in Java

The toString() method in Java is very useful when we want to convert the exact integer into a character. As we saw, this isn't possible using typecasting , but the toString() method does exactly this. Formally, the toString() method in Java returns the integer passed to it in string format.

Why as a string?

If the integer number passed to the toString() method has more than one digit, it won't fit in a character data type.

For example: if our integer is 66 , then the toString() function will return " 66 ", the string. Returning it as a character is not possible, as the character data type would be able to hold the value of only one digit. Hence, this method is useful for integers that have more than one digit.

The syntax for toString() method in Java is:

Here num is an integer variable, and s s s is the resultant string.

Example: int to char by using toString()

As shown by the output, integer 56 has been converted to string " 56 ".

Using forDigit() method in Java

The forDigit() method in Java is used to convert a digit into a character in a specific radix . Here, radix is the base in which we are counting over integer. We need to pass two arguments to the forDigit() function: the digit to be converted into a character and a radix . Then the forDigit() function will return the digit as a character in that radix.

For example, if we call the forDigit() function with the integer value = 11 and the radix = 16, then the function will return the character b , as in radix 16 the value 11 evaluates to the character b .

If the integer value passed to the forDigit() method is not valid in the specified radix, or if the radix is invalid, a null character is returned.

The syntax for the forDigit() method in Java is:

Here, c c c will be the resulting character, n u m num n u m is the integer variable that will be converted to a character, and r a d i x radix r a d i x is the variable that stores the radix/base.

Example: int to char by using forDigit()

As 12 in base 16 is c, forDigit() give the character 'c' as output which is then stored in ch .

By adding '0'

We can also convert an integer into a character in Java by adding the character '0' to the integer data type. This is similar to typecasting .

The syntax for this method is:

Here, c c c is the resultant character, n u m num n u m is the integer variable, and we are adding '0' to n u m num n u m .

This method works because when we add the character ' 0 ' to the integer, it is converted into its ASCII value, which is 48 . This is indirectly converting the value of n u m num n u m to the ASCII value of the character n u m num n u m , and the resulting character is the character whose ASCII value is n u m + 4 8 num + 48 n u m + 4 8 , which will be n u m num n u m itself when the value of n u m num n u m is between 0 and 9.

Clearly, this method will only work for integers from 0 to 9 because above 9 , adding 48 to the integer won't give us its ASCII value, and we will get the wrong answer.

Example: int to char by adding ' 0 '

Conclusion

  • There are four standard ways to convert int to char in Java:
    • using typecasting
    • using toString() method
    • using forDigit() method
    • adding '0'

    Источник

    Converting Between Numbers and Strings

    Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

    The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

    public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >

    The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

    a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5

    Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

    float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);

    Converting Numbers to Strings

    Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

    int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
    // The valueOf class method. String s2 = String.valueOf(i);

    Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:

    int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);

    The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

    public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>

    The output of this program is:

    3 digits before decimal point. 2 digits after decimal point.

    Источник

Оцените статью