Java - Cara Ngonversi String menyang Int Kanthi Conto

Kepiye cara ngowahi String menyang Int ing Jawa? Yen String mung ngemot nomer, mula cara paling apik kanggo ngowahi String dadi Int yaiku nggunakake Integer.parseInt() utawa Integer.valueOf().

Yen String ngemot nomer lan karakter, mula kudu digunakake ekspresi reguler kanggo ngekstrak nomer saka senar banjur ganti String sing diasilake menyang Int.

Siji sing kudu dielingi yaiku parseInt(String) ngasilake int primitif, dene valueOf(String) ngasilake obyek Integer ().




Konversi String dadi Int ing Jawa

Nggunakake Integer.parseInt ()

public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = '1234';
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.parseInt(number);
} }

Output:

1234

Nggunakake Integer.valueOf ()

public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = '1234';
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.valueOf(number);
} }

Output:


1234

Penting, kanggo dicathet yen String ngemot karakter lan angka kayata '1234abcd', banjur Integer parser mbuwang NumberFormatException kaya sing kasebut ing Javadoc .



Gegandhengan:

Nggunakake Integer.decode ()

Kita uga bisa nggunakake Integer.decode(). Fitur sing apik kanggo decode yaiku bisa ngonversi menyang basis liyane, kayata base 10, base 16, lsp.

public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = '1234';
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return Integer.decode(number);
} }

Output:


1234

Kelas Apache CommonsUtils Class

Paling ora, nanging paling ora, kita bisa nggunakake kelas Apache Commons NumberUtils kanggo ngowahi String dadi Int ing Jawa.

Sampeyan mung kudu duwe katergantungan ing ngisor iki ing pom.xml ngajukake


org.apache.commons
commons-lang3
3.9

Banjur, sampeyan bisa nggunakake:

import org.apache.commons.lang3.math.NumberUtils; public class ConvertStringToInt {
public static void main(String[] args) {
String stringNumber = '1234';
int number = convertStringToInt(stringNumber);
System.out.println(number);
}
private static int convertStringToInt(String number) {
return NumberUtils.toInt(number);
} }

Output:


1234