1

This is my program...

import java.lang.Math;
class SquareRoot
{
  public static void main(String args[])
  {
    try
    {
      System.out.println("Enter A Number To Find its Square Root");
      System.out.flush();
      double x = (double) System.in.read();
      double y;
      y = Math.sqrt(x);
      System.out.println("Square Root of " + x + " is " + y);
    }
    catch (Exception e)
    {
      System.out.println("I/O Error! Humein Maaf Kar Do Bhaaya");
    }
  }
}

If I enter 75 as input it shows.. Square Root of 55.0 is <55's square root>
On entering 23 it shows Square Root of 50.0. Where am I wrong? No problems in compilation.

I am using DrJava IDE. JDK 7u25 Compiler. Windows 7 32 bit.

4
  • 2
    User input is done wrong. Use a Scanner instead of System.in directly. Commented Aug 8, 2013 at 15:13
  • How to do it correctly..? I am new with Java. Commented Aug 8, 2013 at 15:14
  • ASCII of 7 (in 75) is 55, while ASCII of 2 (in 23) is 50 Commented Aug 8, 2013 at 15:14
  • import java.lang.Math isn't needed, the java.lang package is implicitly imported Commented Aug 8, 2013 at 15:18

4 Answers 4

8

System.in.read() returns one character. Then its integer representation casted to double.

You may use BufferedReader:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
double number = Double.parseDouble(s);

Or Scanner:

Scanner scanner = new Scanner(System.in);
double number = scanner.nextDouble();
Sign up to request clarification or add additional context in comments.

1 Comment

Or Scanner for simplicity of code and avoid parsing String to the data I want/need.
4
double x = (double) System.in.read();

Nope. I would recommend wrapping this up in a Scanner.

Scanner s = new Scanner(System.in);
double x = s.nextDouble();
String str = s.nextLine(); // <-- Just an example!

Just makes for much nicer code!

Remember

Put import java.util.Scanner at the top of your page, otherwise Java will kick up a bit of a fuss!

6 Comments

There is no need to assign s.nextLine() to a string if you are using it just to empty the buffer
I was just using that as an example of it's usage.
What is String str for?
Just an example of it's usage. Wow I didn't think it would be this confusing :P
@GunJack did you import java.util.Scanner?
|
2

The problem is that when you are casting as a double when getting the user input, it is converting the first character in the input into its ascii value. ('7' = 55, '2' = 50)

Comments

1

Use follows:

Scanner s = new Scanner(System.in);
double x = s.nextDouble();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.