Java cast num to type int | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Java cast num to type int

I can't figure out how to cast num to int. My code works when user entering an integer, but when a float number entered it gives me : Enter an integer: 4.4 Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Assignments.KeybInp.main(KeybInp.java:8) Here is my code: https://code.sololearn.com/cep7rPdino9d/#java I have to cast the result to int and display it. This is my first assignment and I stuck. Help me to move on, please! Regards!

14th Jan 2018, 9:36 PM
DIY Mods
DIY Mods - avatar
4 Answers
+ 6
Maybe you can change int number = scanner.nextInt(); to double number = scanner.nextDouble(); And change the type of value from double to int.
14th Jan 2018, 9:56 PM
Jente
+ 11
InputMismatchException was triggered because you try to assign a floating point number into an integer, @Jente's suggestion was right, you should be ready for such possibilities where integer was expected, yet floating points were given, and one of the ways to do that would be to use floating point type, which you can later try to cast to integer. import java.util.Scanner; public class KeybInp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); // Accept input as double in order to // cope with floating point input possibility double number = scanner.nextDouble(); scanner.close(); System.out.println("The number is: " + number); System.out.println("The number converted to int " + (int)number); } } Hth, cmiiw
14th Jan 2018, 10:02 PM
Ipang
+ 2
Thank you for the reply! if I understanding correctly, int has to be a round number without a dot. It gives me for instance 7.0 while I need just 7
14th Jan 2018, 10:00 PM
DIY Mods
DIY Mods - avatar
+ 2
Ok, I did it! Thank you very much again! I changed int to double as you said and added (int) to System.println: System.out.println("The number is: " + (int)value);
14th Jan 2018, 10:06 PM
DIY Mods
DIY Mods - avatar