Wednesday, August 29, 2018

java - nextDouble() throws an InputMismatchException when I enter a double



import java.util.*;

class Averager
{
public static double unlimited()
{
int count = 0;
double sum = 0;
Scanner scan = new Scanner(System.in);
while(scan.hasNext())
{
double d = scan.nextDouble();
sum += d;
count++;
}
double ave = sum/count;
return ave;
}

public static void main(String[] args) {
System.out.println(unlimited()+"\n");
}
}


There is no error when I use integers but if I use numbers with point in it a error appears.



$ javac Averager.java; java Averager
0.5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at Averager.unlimited(Averager.java:12)
at Averager.main(Averager.java:21)


To my best understanding 0.5 should be covered by double. If not please can someone correct me.


Answer



It might be locale dependent. Decimal numbers are e.g written as 0,5 in Sweden.



Change your code so that it says e.g.:



Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.US);

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...