8
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.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Helgi
  • 338
  • 2
  • 5
  • 11

2 Answers2

29

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);
Kaj
  • 10,862
  • 2
  • 33
  • 27
  • 8
    Hm, not sure about how this site is working since I never have asked a questio, but I think there is something next to my post that you should tick in order to say that the answer was correct :) – Kaj May 08 '11 at 17:59
0
This worked for me, changing the locale did not.

  Scanner sc = new Scanner(System.in);
  // val = sc.nextDouble(); - crashes with java.util.NoSuchElementException
  // If Java crashes with legal Java code, wrap the call in a hasNextLine() test
  if (sc.hasNextLine())
  {
    val = sc.nextDouble();
  }

java.util.NoSuchElementException: No line found

Community
  • 1
  • 1
  • Sorry for the post: the code continued to not work. I believe there is a bug in the Java compiler with the Scanner. javac -version gave 1.8.0_60 – Chelton Sep 03 '15 at 07:04