Reputation: 1418
Here is my code for my scanner:
import java.util.Scanner;
public class TryDouble {
public static void main(String [] args){
Scanner jin = new Scanner(System.in);
double a = jin.nextDouble();
double b = jin.nextDouble();
double c = jin.nextDouble();
System.out.println(a + b + c);
}
}
For input: 0.2 0.5 0.9, I got:
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.nextDouble(Unknown Source)
at TryDouble.main(TryDouble.java:6)
What can I do to remove that error?
Upvotes: 5
Views: 1777
Reputation: 206
It's a locale issue : If you want to use . you can try something like :
package test;
import java.util.Locale;
import java.util.Scanner;
public class TryDouble {
public static void main(String [] args){
Scanner jin = new Scanner(System.in).useLocale(Locale.US);
double a = jin.nextDouble();
double b = jin.nextDouble();
double c = jin.nextDouble();
System.out.println(a + b + c);
}
}
Upvotes: 5
Reputation: 30849
This Exception is thrown when someone enters something other than a double. I tried entering 'a' and was able to see the exception.
Ideal way is to get the input as String using next(), validate it and show error message if it is not a number.
The example also has a resource leak as Scanner is not closed. Below is an exmple of how to do it:
public static void main(String [] args){
Scanner jin = null;
try{
jin = new Scanner(System.in);
//logic
}finally{
jin.close();
}
}
Upvotes: 0