+ 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
3 Respuestas
+ 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("?");
}
}
}
+ 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
+ 1
Thank you