+ 1

From string to int in java

int mph; int speed = (int) mph; System.out.println("What is your current speed?"); mph = in.nextLine() How do I convert the int from a string, when I use my scanner? The error states: Type mismatch: cannot convert from String to int

27th Mar 2018, 3:32 AM
Mathew Henson
3 Respostas
+ 6
If a user enters a String instead of int, use Exception handling import java.util.Scanner; class MyClass { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); try{ System.out.println(sc.nextInt()); } catch(java.util.InputMismatchException e){ System.out.println("?"); } } }
27th Mar 2018, 1:45 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 2
if you want an integer input from Scanner, use nextInt() method. Scanner s = new Scanner(System.in); int mph = s.nextInt(); for reference you can see the below code: https://code.sololearn.com/czaZjwJ5fBz1/?ref=app
27th Mar 2018, 3:43 AM
Nilesh
Nilesh - avatar
+ 1
Thank you
27th Mar 2018, 4:30 AM
Mathew Henson