我正在使用lambda表达式,并试图创建一个通用的函数接口,该接口采用双精度值并将其返回为整数值。但是,然后我得到一个错误NumberFormatException或无法强制转换。如果我使用(int)(Math.random)之类的方法,则它将双精度值完美地转换为整数,但这是我的代码和出现的错误:
package Exercise;
public class Training {
public static void main(String[] args) {
Training4<Integer, Double> obj = (x) -> Integer.parseInt(x.toString());
System.out.println(obj.constrmeth(10.5));
}
}
这是功能界面:
package Exercise;
public interface Training4 <T, S>{
T constrmeth(S a);
}
错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10.5"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Exercise.Training.lambda$0(Training.java:9)
at Exercise.Training.main(Training.java:10)
答案 0 :(得分:0)
**Here if you use Double then you can easily get int value **
package com.example.demo;
public class TEST {
public static void main(String[] args) {
Training4 obj = (x) -> x.intValue();
System.out.println(obj.constrmeth(10.5));
}
}
interface Training4 {
public Integer constrmeth(Double db);
}