-2

i'm working with lambda expressions and tried to make a generic functional interface where the interface takes a double value and returns that into an integer value. But then i get an error NumberFormatException or cannot cast error. If i use an method like (int)(Math.random) then it casts the double values perfectly into a integer, but here is my code and the errors i get:

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));
    }
}

and here is the functional interface:

package Exercise;
public interface Training4 <T, S>{

    T constrmeth(S a);
}

Error:

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)
azro
  • 53,056
  • 7
  • 34
  • 70
syclone
  • 99
  • 13
  • 2
    an Integer can't have decimals. a Double isn't an Integer, and can not be cast to it. the error message is quite self-explanatory – Stultuske Jan 16 '19 at 10:15
  • Replace `Integer.parseInt(x)` with `Double.parseDouble(x)`. More details in [Double#parseDouble](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html#parseDouble-java.lang.String-) –  Jan 16 '19 at 10:16
  • Hint: there is no **casting** here. Only parsing. Words matter. – GhostCat Jan 16 '19 at 10:16
  • 1
    @GhostCat according to the original title, there was :) – Stultuske Jan 16 '19 at 10:17
  • Hint 2: try to be consistent with standard java classes. When you look at https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html you find that your two generic parameters ... are "reversed" and naming could be improved to. LIke "R" for Result ;-) – GhostCat Jan 16 '19 at 10:19
  • @Stultuske thats only if an functional interface is generic. For this problem i yust used IntValue() – syclone Feb 03 '19 at 00:51

1 Answers1

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);


}
abhinavsinghvirsen
  • 1,853
  • 16
  • 25