В этом уроке мы увидим различные способы преобразования String в int (или Integer) в Java.
Вы можете использовать любой из следующих способов:
— Использование Integer.parseInt (строка)
— Использование Integer.valueof (строка)
— Использование Apache Comms NumberUtils.toInt (строка)
— Использование общих Apache NumberUtils.createInteger (строка)
— Использование метода Ints.tryParse (string) библиотеки Guava
— Использование Integer.decode (строка)
— Использование нового целого числа (строка)

Использование Integer.parseInt (строка)
|
1
2
3
4
5
6
|
String empId1 = "1001";int intEmpId1 = Integer.parseInt(empId1);System.out.println(intEmpId1);Output :1001 |
Integer.parseInt () вызовет исключение NumberFormatException в следующих случаях:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
/ Alphabets in the input. Integer.parseInt("100AB");//Input number is greater than the Integer range. Integer.parseInt("2147483648"); //Number with decimal Integer.parseInt("1.1"); //empty String Integer.parseInt(""); //Blank space Integer.parseInt(" "); |
Использование Integer.valueof (строка)
|
1
2
3
4
5
6
7
|
String empId2 = "2001";Integer integerEmpId2 = Integer.valueOf(empId2);System.out.println(integerEmpId2);Output :2001 |
Использование Apache Commons NumberUtils.toInt (строка)
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
String empId3 = "3001";int intEmpId3 = NumberUtils.toInt(empId3);System.out.println(intEmpId3);Output :3001 int intEmpId4 = NumberUtils.toInt(null);System.out.println(intEmpId4);Output :0 int intEmpId5 = NumberUtils.toInt("1001ABC");System.out.println(intEmpId5);Output :0 int intEmpId6 = NumberUtils.toInt("1001ABC", 10);System.out.println(intEmpId6);Output :10 |
Использование Apache Comms NumberUtils.createInteger (строка)
|
1
2
3
4
5
6
|
String empId4 = "4001";Integer integerEmpId7 = NumberUtils.createInteger(empId4);System.out.println(integerEmpId7);Output :4001 |
Использование метода Ints.tryParse (string) библиотеки Guava
|
1
2
3
4
5
6
7
|
String empId5 = "5001";Integer integerEmpId8 = Ints.tryParse(empId5);System.out.println(integerEmpId8);Output :5001 |
Использование Integer.decode (строка)
|
1
2
3
4
5
6
|
String empId6 = "6001";Integer integerEmpId9 = Integer.decode(empId6);System.out.println(integerEmpId9);Output :6001 |
Используя новое целое число (строка)
|
1
2
3
4
5
6
|
String empId7 = "7001";Integer integerEmpId10 = new Integer(empId7);System.out.println(integerEmpId10);Output :7001 |
Однако помните, что этот конструктор Integer устарел с Java9.
Полная программа
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package com.blogspot.javasolutionsguide.stringtointexample;import org.apache.commons.lang3.math.NumberUtils;import com.google.common.primitives.Ints;public class StringToInt { public static void main(String[] args) { String empId1 = "1001"; int intEmpId1 = Integer.parseInt(empId1); System.out.println(intEmpId1); String empId2 = "2001"; Integer integerEmpId2 = Integer.valueOf(empId2); System.out.println(integerEmpId2); String empId3 = "3001"; int intEmpId3 = NumberUtils.toInt(empId3); System.out.println(intEmpId3); int intEmpId4 = NumberUtils.toInt(null); System.out.println(intEmpId4); int intEmpId5 = NumberUtils.toInt("1001ABC"); System.out.println(intEmpId5); int intEmpId6 = NumberUtils.toInt("1001ABC", 10); System.out.println(intEmpId6); String empId4 = "4001"; Integer integerEmpId7 = NumberUtils.createInteger(empId4); System.out.println(integerEmpId7); String empId5 = "5001"; Integer integerEmpId8 = Ints.tryParse(empId5); System.out.println(integerEmpId8); String empId6 = "6001"; Integer integerEmpId9 = Integer.decode(empId6); System.out.println(integerEmpId9); String empId7 = "7001"; Integer integerEmpId10 = new Integer(empId7); System.out.println(integerEmpId10); // Alphabets in the input. Integer.parseInt("100AB"); //Input number is greater than the Integer range. Integer.parseInt("2147483648"); //Number with decimal Integer.parseInt("1.1"); //empty String Integer.parseInt(""); //Blank space Integer.parseInt(" "); }} |
Используемые зависимости:
|
01
02
03
04
05
06
07
08
09
10
11
12
|
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version></dependency><dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>16.0.1</version></dependency> |
Резюме
Итак, в этом уроке мы увидели
— Как мы можем конвертировать String в int (или Integer) в Java.
— В большинстве сценариев мы можем использовать Integer.parseInt () и Integer.valueOf (), если мы хотим int или Integer
соответственно от String и хотят избежать зависимости от сторонних библиотек.
— NumberUtils. toInt () может использоваться в сценариях, где мы не хотим, чтобы наша программа не работала из-за NumberFormatException.
|
Опубликовано на Java Code Geeks с разрешения Гаурава Бхардваджа, партнера нашей программы JCG . Смотрите оригинальную статью здесь: Как конвертировать String в int в Java Мнения, высказанные участниками Java Code Geeks, являются их собственными. |