我有以下代码,它适用于整数,但在输入字符串时抛出以下异常:
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)
只允许整数的最佳方法是什么?
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);
try{
if(input < 100){
double total = input += input * .02;
System.out.println(total);
}else{
double total = input;
System.out.println(total);
}
}catch(NumberFormatException e){
System.out.print("You must enter a number");
}
}
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();
}
}
}
答案 0 :(得分:8)
我建议在try-catch
周围设置一个Integer.parseInt()
块。这样你知道错误是否为java.lang.NumberFormatException
类型,并且可以处理这种情况,而不会限制程序暂停执行和退出其他输入错误的能力。
只需专门为catch
设置java.lang.NumberFormatException
块,以便不会忽略其他错误:
catch(NumberFormatException e){/*print an error message to user etc.*/}
答案 1 :(得分:0)
在解析之前,检查字符串变量s1是否包含数字 在Apache常见的NumberUtils中,有一种检查方法。
NumberUtil.isNumber(String str)
答案 2 :(得分:0)
你可以看到整数的JAVA api。它表明方法parseInt(String s)的参数s应该是Number.Just见下文:
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;
}
答案 3 :(得分:0)
试试这个:
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();
}
}
}