A NumberFormatException is thrown when a string cannot be parsed into a number in Java. Here are some common ways to solve this exception:
Check the input format: Ensure that the string being parsed is in the correct format for the type of number you want to parse. For example, if you are trying to parse an integer, the string should only contain digits and should not have any decimal points or letters.
Use the correct parsing method: Make sure you are using the correct method to parse the string into a number. For example, you can use Integer.parseInt(string) to parse a string into an integer, or Double.parseDouble(string) to parse a string into a double.
Catch the exception: Use a try-catch block to catch the NumberFormatException and handle it appropriately. You can either return an error message or use a default value for the number in case of an exception.
Here's an example that demonstrates how to catch a NumberFormatException:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
String input = sc.nextLine();
try {
int number = Integer.parseInt(input);
System.out.println("The number is: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
}
}
In this example, the try-catch block is used to catch the NumberFormatException and handle it by printing an error message to the user. The parseInt method is used to parse the input string into an integer, and the result is stored in the number variable.
No comments:
Post a Comment