Reputation: 5487
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();
}
}
}
Upvotes: 2
Views: 14496
Reputation: 9093
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.*/}
Upvotes: 9
Reputation: 552
Try this:
package shipcost;
import java.io.*;
//Your class should be ShipCost (All words starting with uppercase)
public class ShipCost {
public static void main(String[] args) {
//Declare and initialize your variables first (with invalid values for your program)
double input = -1;
double total = 0;
String s1 = null;
//This will loop to prompt the user until the input is correct
while (true) {
try {
//try to execute the folowing lines
s1 = getInput("enter the item price");
input = Integer.parseInt(s1);
//If everything went fine, break the loop and move on.
break;
} catch (NumberFormatException e) {
//If the method Integer.parseInt throws the exception, cathc and print the message.
System.out.println("Not a valid input, please try again.");
}
}
if (input < 100) {
//What is this line exactly doing?
//double total = input += input * .02;
//This is better. If input less than 100, charge 2% over the price.
total = input * 1.02;
System.out.println(total);
//How can you return something from a void method (in this case main).
//The statement below will not compile
//return stdin.readLine();
} else {
//If greater than or equal to 100, do not charge shiping.
total = input;
System.out.println(total);
}
}
private static String getInput(String prompt) {
//Comment your code for your own good, it makes more readable and helps you in future ref.
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
//Separate your line in chunks for commenting.
System.out.print(prompt);
System.out.flush();
try {
return stdin.readLine();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
}
Upvotes: 0
Reputation: 1
You can see the JAVA api for Integer. It shows that parameter s for method parseInt(String s) should be Number.Just see below:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static int parseInt(String s, int radix)
throws NumberFormatException {
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
Upvotes: 0
Reputation: 63
Before parsing, check String variable s1 contains number or not in Apache common NumberUtils, there is a method to check this.
NumberUtil.isNumber(String str)
Upvotes: 0