readDouble(); java programming

I tried to read the double value using read-double function but its reading as some other value, I gave the input as 15.00 it read as 825568816. please help me to get it correct.

    DataInputStream din=new DataInputStream(System.in);
    double d=din.readDouble();
    System.out,println(d);
Jon Skeet
people
quotationmark

Basically, don't use DataInputStream if you're trying to read text. DataInputStream is meant for streams of data written by DataOutputStream or something similar. Read the documentation for readDouble to see exactly what it's doing.

Options for you:

  • Use Scanner and its nextDouble() method: my experience of questions on Stack Overflow is that Scanner is frankly a pain to use correctly
  • Create a BufferedReader wrapping an InputStreamReader, and then call readLine() to get a line of text, and Double.parseDouble() to parse that into a double.
  • A hybrid approach: use Scanner, but only to call nextLine() - just a simpler way to read lines of text from System.in, basically.

Additionally, you might want to consider using BigDecimal - the value "15.00" sounds like it might be a financial value (e.g. a price) - and those should be stored in BigDecimal as that can represent exact decimal values.

people

See more on this question at Stackoverflow