0
System.out.println("Enter a number: ");

String in1 = input.nextLine();

Integer input1 = Integer.valueOf(in1);
Float input2 = Float.parseFloat(in1);
Double input3 = Double.valueOf(in1).doubleValue();

System.out.println();
System.out.println("Enter another number: ");

String in2 = input.nextLine();
Integer input21 = Integer.valueOf(in2);
Float input22 = Float.parseFloat(in2);
Double input23 = Double.valueOf(in2).doubleValue();

FloatN fco = new FloatN();

System.out.println();
System.out.println("The sum of both of your numbers is: " + fco.add(input2, input22));
done = true;

我很清楚这个程序是完全不切实际的,我写它只是为了练习解析、泛型和接口。我尝试了 Integer,效果很好,但是在尝试 Float 和 Double.add() 函数时,我得到 3 个错误:

在 java.lang.NumberFormatException.forInputString

在 java.lang.Integer.parseInt

在 java.lang.Integer.valueOf

我删除了整数解析器,程序运行良好。我很困惑为什么我只有在输入 Decimal 值时才会收到错误,并且希望有人帮助指出究竟是什么导致了异常,这样我就可以在将来避免这样的任何错误,因为删除 Integer 解析器会删除IntegerN 类的任何功能。

此外,如果有人出于某种原因需要 FloatN 类:

public static class FloatN implements Summization<Float>{
    public FloatN(){}
    public Float add(Float a, Float b)
    {
        return a + b;
    }
}

求和是一个带有 add() 方法的通用接口。

提前致谢。

4

4 回答 4

2

如果输入十进制值作为输入,Integer.parseInt()方法将无法解析它。如果您仍然希望将它们全部包含在代码中,则必须获取该值的 intFloat值。您可以使用intValue()方法:

    Float input2 = Float.parseFloat(in1);
    Integer input1 = Integer.valueOf(input2.intValue());
于 2013-12-12T07:20:34.687 回答
1

因为Integer.valueOf(in2);这条线会给 NumberFormatException ,floatdouble可以使用

Number num = NumberFormat.getInstance().parse(myNumber);

见@http ://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html

于 2013-12-12T07:11:39.820 回答
1

也许添加不包含可解析浮点数的字符串或者它为空。

来自 javadoc:

NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable float.
于 2013-12-12T07:14:57.990 回答
0

NumberFormatException 出现在 Integer 解析器中,如果输入包含小数,则不在 Double 和 Float 解析器中。

在这种情况下,您可以使用split和 parse获得十进制数的整数部分:

    String[] s = in1.split("\\.");
    Integer input1 = Integer.valueOf(s[0]);
    Float input2 = Float.parseFloat(in1);
    Double input3 = Double.valueOf(in1).doubleValue(); 
于 2013-12-12T07:33:12.020 回答