IJava -Uwuguqula njani umtya ungene kwi-Int Ngemizekelo

Ungawuguqula njani umtya ube yi-Int kwiJava? Ukuba umtya unamanani kuphela, eyona ndlela yokuguqula umtya uye kwi-Int kukusebenzisa Integer.parseInt() okanye Integer.valueOf().

Ukuba umtya uqukethe amanani kunye nabalinganiswa, kuya kufuneka sisebenzise amabinzana aqhelekileyo okukhupha amanani ukusuka kumtya kwaye emva koko uguqule isiphumo sokuSifaka kwi-Int.

Inye into ekufuneka uyiqaphele kukuba parseInt(String) ibuyisa into yakudala, ngelixa valueOf(String) Ibuyisela iNaniger () into.




Guqula umtya ube yi-Int kwiJava

Sebenzisa iNeger.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);
} }

Iziphumo:

1234

Sebenzisa iNeger.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);
} }

Iziphumo:


1234

Kubalulekile ukuba uqaphele ukuba ukuba umtya uqulethe abalinganiswa kunye neenombolo ezinje ngo '1234abcd' emva koko i-Integer parser iphosa iNomboloFormatException njengoko kuchaziwe IJavadoc .



Idibeneyo:

Sebenzisa i-Integer.decode ()

Sinokusebenzisa Integer.decode(). Inqaku elinomdla le decode kukuba ingaguqulela kwezinye iziseko, ezinje nge base 10, base 16, njl.

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

Iziphumo:


1234

Iklasi yeApache Commons

Okokugqibela kodwa kungaphelelanga apho, sinokusebenzisa iklasi yeApache Commons NumberUtils ukuguqula umtya uye kwi-Int kwiJava.

Konke okufuneka ukwenze kukuba nokuxhomekeka koku kulandelayo pom.xml ifayile


org.apache.commons
commons-lang3
3.9

Emva koko, ungasebenzisa:

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

Iziphumo:


1234