PDA

View Full Version : What does it mean by the term :Type mismatch: cannot convert from double to float


A Lonely Star
Nov 22, 2013, 01:16 AM
1. Hi, Iam a beginner in the amazing world of programming . And I am trying to learn JAVA on my own. While practicing , using abstract method I wrote this code to calculate the area of some geometrical figures. But the compiler gave the message :

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from double to float

at Shape.<init>(AbstractMethodDemo.java:6)
at Square.<init>(AbstractMethodDemo.java:15)
at AbstractMethodDemo.main(AbstractMethodDemo.java:60 )

but after trying hard I can't make out what's the problem here with double and float. Please could you give me an explanation ? Help me please

2.code:

abstract class Shape
{
public static float pi = 3.142;
protected float height;
protected float width;

abstract float area();
}

class Square extends Shape
{
Square(float h, float d)
{
height = h;
width = d;
}

float area()
{
return height * width;
}
}

class Rectangle extends Shape
{
Rectangle(float h, float w)
{
height = h;
width = w;
}

float area()
{
return height * width;
}
}

class Circle extends Shape
{
float radius;

Circle(float r)
{
radius = r;
}

float area()
{
return Shape.pi * radius *radius;
}
}

public class AbstractMethodDemo
{
public static void main(String args[])
{
Square sObj = new Square(5,5);
Rectangle rObj = new Rectangle(5,7);
Circle cObj = new Circle(2);

System.out.println("Area of square : " + sObj.area());
System.out.println("Area of rectangle : " + rObj.area());
System.out.println("Area of circle : " + cObj.area());
}
}

Scleros
Nov 30, 2013, 04:57 AM
The compiler found an object of type double where it needed a type of float, hence the type mismatch. The compiler tells you the line numbers of the errors. What compiler are you using? The Oracle command line compiler shows the exact error position.

You can either cast the double to a float or change the float to a double.

Also read Data Types (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html) and note the info about double and where it would apply in your code.