0
How to convert numeric String to int in Java?
3 odpowiedzi
+ 2
https://code.sololearn.com/cfGRKGVQXJPA/#java
public class Program
{
public static void main(String[] args) {
String numString = "123";
try {
System.out.println(Integer.parseInt(numString));
System.out.println(Integer.valueOf(numString));
System.out.println(Integer.decode(numString));
} catch (NumberFormatException e) {
System.out.println("Error: Not a number string!");
}
numString = "abc";
try {
System.out.println(Integer.parseInt(numString));
System.out.println(Integer.valueOf(numString));
System.out.println(Integer.decode(numString));
} catch (NumberFormatException e) {
System.out.println("Error: Not a number string!");
}
}
}
^That's 3 different ways to convert the string to an int. As well, it also checks to ensure the input is a number string and catches the NumberFormatException so our program doesn't crash if the string isn't a number.
+ 3
String numericString = "1234";
int number = Integer.parseInt(numericString);