I have the following code, which works well with integers, but throws the following exception when a string is entered:
Exception in thread "main" java.lang.NumberFormatException: For input string: "henry"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at shipCost.java.shipCost.main(shipCost.java:13)
What would be the best approach to only allowing integers?
package shipCost.java;
import java.io.*;
public class shipCost {
public static void main(String[] args) {
String s1 = getInput("enter the item price");
double input = Integer.parseInt(s1);
if(input < 100){
double total = input += input * .02;
System.out.println(total);
return stdin.readLine();
}else{
double total = input;
System.out.println(total);
}
}
private static String getInput(String prompt)
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try{
return stdin.readLine();
} catch (Exception e){
return "Error: " + e.getMessage();
}
}
}
I would recommend a try-catch block around Integer.parseInt(). That way you know if the error is of type java.lang.NumberFormatException and can deal with that case without limiting your program's ability to halt execution or quit on other input errors.
Simply make your catch block for java.lang.NumberFormatException specifically so that other errors are not caught:
catch(NumberFormatException e){/*print an error message to user etc.*/}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With