简体   繁体   中英

Simple Java Program Strange Output

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.

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();
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!

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

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)

Use follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM