Рет қаралды 211
In Java, you can convert a String to an int using the parseInt() method of the Integer class or by using the valueOf() method. Here's how:
Use Integer.parseInt():
String str = "123";
int number = Integer.parseInt(str);
Use Integer.valueOf():
String str = "123";
int number = Integer.valueOf(str);
Both methods will throw a NumberFormatException if the string does not contain a parsable integer. You can handle this exception using a try-catch block:
try {
String str = "123";
int number = Integer.parseInt(str);
// Use 'number' variable here
} catch (NumberFormatException e) {
// Handle the exception
System.err.println("Input is not a valid integer");
}
Make sure to handle the NumberFormatException appropriately in your code to prevent unexpected errors.