Java - Maitiro Ekushandura Tambo kuita Int Nemienzaniso

/ Ungashandura sei Tambo kuita Int muJava? Kana iyo Tambo iine chete nhamba, saka nzira yakanakisa yekushandura iyo Tambo kuenda kuInt ndeye kushandisa Integer.parseInt() kana Integer.valueOf().

Kana iyo Tambo iine ese ari maviri manhamba uye mavara, saka isu tinofanirwa kushandisa mataurirwo enguva dzose kutora nhamba kubva patambo uye wozoshandura iyo inoguma String iyo kuInt.

Chinhu chimwe chete chekucherechedza ndechekuti parseInt(String) inodzosera yechinyakare int, nepo valueOf(String) inodzosera iyo Integer () chinhu.

Chinja Tambo kuenda kuInt muJava

Uchishandisa 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);
} }

Kubuda:

1234

Uchishandisa 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);
} }

Kubuda:

1234

Izvo zvakakosha kuti uzive kuti kana iyo Tambo iine mavara uye nhamba dzakadai se '1234abcd' ipapo iyo Integer parser inokanda NumberFormatException sezvakataurwa mu Javadoc .



Inoenderana:

Uchishandisa Integer.decode ()

Tinogona zvakare kushandisa Integer.decode(). Chinhu chinonakidza che decode ndeyekuti inogona kushandukira kune mamwe mabhesi, senge base 10, base 16, nezvimwe…

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);
} }

Kubuda:

1234

Apache Commons NhambaUtils Kirasi

Chekupedzisira asi chisiri chidiki, tinogona kushandisa Apache Commons NumberUtils kirasi kushandura String kuenda Int muJava.

Zvese zvaunoda kuti uite kuve neinotevera kutsamira mune yako pom.xml faira


org.apache.commons
commons-lang3
3.9

Ipapo, unogona kushandisa:

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);
} }

Kubuda:

1234