Write the Java code
Next, we will write the Java code in the newly created file ParseIntMethod.java
.
import java.util.Scanner;
public class ParseIntMethod {
public static void main(String[] args) {
try {
System.out.print("Enter the value: ");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.print("Enter the radix: ");
int radix = sc.nextInt();
System.out.println("Entered value and Base value is: " + s + " and " + radix);
System.out.println("Equivalent Integer object is " + Integer.parseInt(s, radix));
} catch (NumberFormatException e) {
System.out.println("Invalid Input!!");
}
}
}
In the above code, we have created a class named ParseIntMethod
that contains the main()
method. The program prompts the user to enter a string value and a radix value. Then, it will parse the string value into a signed integer value relative to the radix value that the user has input. Finally, the program will display the equivalent signed integer value as the output. If the user inputs an invalid value, the program will catch the exception and print "Invalid Input!!".