This question already has answers here:
How to make the division of 2 ints produce a float instead of another int?
(9 answers)
Closed 5 years ago.
I have a problem in floats. My 1st problem is my public float area(), the problem is the result value is returning zero. 2nd is the public float computeHeight(), no value will return. I'm having headache with this. please help me thank you. Just delete if duplicate or repost. thank you
private int sideA, sideB, sideC;
private float computePerimeter;
private float area;
private float computeHeight;
public Triangle(){
}
// I want to set all sides to 10
public Triangle(int a, int b, int c){
sideA = a;
sideB = b;
sideC = c;
}
//setters & getters
//perimeter is the sum of all the sides of the triangle.
public float computePerimeter(){
computePerimeter = sideA + sideB + sideC;
return computePerimeter;
}
//A=1/2bh.
//A = Area of the triangle
//b = Length of the base of the triangle //SideB
//h = Height of the base of the triangle //SideA
public float area(){
area = 1/2 * (sideB * sideA);
return area;
}
public float computeHeight(){
sideC = 2 * (area/sideB) ;
return computeHeight;
}
public void display(){
System.out.println("Side A: "+getSideA() +" Side B: "+getSideB()+" Side C: "+getSideC() );
System.out.println("\nThe sum of all the sides of the triangle is: " +computePerimeter() );
System.out.println("The area of the triangle is: " + area() );
}
public static void main(String []args){
Triangle result = new Triangle();
result.setSideA(10);
result.setSideB(10);
result.setSideC(10);
result.display();
}
Maybe:
public float area(){
area = (float) (0.5f * (sideB * sideA));
return area;
}
public float computeHeight(){
sideC = 2f * (area/sideB) ;
return computeHeight;
}
Adding the "f" and the casting makes the numbers to be treated as a float.
Related to: I don't know how to cast to float in Java.
If you don't do this, then the number is processed as if it was an integer (1/2 in integer world = 0). Thus you lose a lot of precision.
1/2 return 0 because they are int, you need to use (1.0 / 2)
Also I would advise to replace all your float and int by double (for the 6 attributes) , it would allow you to not have warning possible loss convertion' to avoid casting(float)and usef` after the number
private double sideA, sideB, sideC, computePerimeter, area, computeHeight;
And a trick I'd learn to you, this will will assign the result to area AND return it :
public double area() {
return (area = 1.0 / 2 * (sideB * sideA));
}
Last thing, because you have a public Triangle(double a, double b, double c) constructor you may replace
Triangle result = new Triangle();
result.setSideA(10);
result.setSideB(10);
result.setSideC(10);
By Triangle result = new Triangle(10,10,10); in one-line
Related
My teacher gave me this
In a n - sided regular polygon, all sides have the same length and all angles have the same degree. Design a class named RegularPolygon that contains:
A private int data field named n that defines the number of sides in the Polygon with default value 3.
A private double data field named side that stores the length of the side with default value 1.
A private double data field named X that defines the x - coordinate of the polygon’s center with default value 0.
A private double data field named Y that defines the y - coordinate of the polygon’s center with default value 0.
A constructor that creates a regular polygon with the specified number of sides, length of side, and x - and y- coordinates (values are passed from the parameters to the fields).
The accessor methods for all data fields.
The method getPerimeter() that returns the perimeter of the polygon.
The method getArea() that returns the area of the polygon. The formula is Area = n * s*s / (4 * tan(PI / n)).
2) Write a RegularPolygonTest class, allow the user to enter the data fields, and your program prints out the perimeter and the area of the regular polygon.
This is my code so far:
public class RegularPolygon{
private int n;
private double side, x, y;
public RegularPolygon(){
n = 3;
side = 1;
x = 0;
y = 0;
}
public RegularPolygon(int n, double side){
this.n = n;
this.side = side;
x = 0;
y = 0;
}
public RegularPolygon(int sn, double length, double x_coord, double y_coord){
n = sn;
side = length;
x = x_coord;
y = y_coord;
}
//set n to the user input
public void setN(int other){
n = other;
}
public int getN(){
return n;
}
//set side to userinput
public void setSide(double otherside){
side = otherside;
}
public double getSide(){
return side;
}
//set x to user input
public void setX(int x_co){
x = x_co;
}
public double getX(){
return x;
}
//set y to user input
public void setY(int they){
y = they;
}
public double getY(){
return y;
}
//find perimeter
public double getPerimeter(){
return n * side;
}
//find area
public double getArea(){
double s_squ = side * side;
double pin = Math.PI/n;
double tangent = Math.tan(pin);
return (n*s_squ)/(4*tangent);
}
}
import java.util.Scanner;
public class RegularPolygonTest{
public static void main(String[] args){
Scanner yer = new Scanner(System.in);
//number of sides
System.out.println("Enter number of sides: ");
int sn = yer.nextInt();
//length of sides
System.out.println("Enter length of sides: ");
double length = yer.nextDouble();
//x-coord
System.out.println("Enter the x-coordinate of the center: ");
double x_coord = yer.nextDouble();
//y-coord
System.out.println("Enter the y-coordinate of the center: ");
double y_coord = yer.nextDouble();
if (x_coord == 0 && y_coord == 0){
RegularPolygon rp = new RegularPolygon(sn, length);
}
else if (sn > 3 && length > 1){
RegularPolygon rp = new RegularPolygon(sn, length, x_coord, y_coord);
}
else{
RegularPolygon rp = new RegularPolygon();
}
System.out.println("The perimeter of the " + rp.getN() + "-sided polygon is : "+ rp.getPerimeter() +". And the are is : "+ rp.getArea());
}
}
The error I get is that the IDE can't find symbol and it points to all of the rp in the last line. How might I fix this error?
All the rp are inside blocks. You need to define a possibly uninitialized rp before the ifs and use this common rp within the ifs.
Here is my class. In the main method at the bottom I pass two arguments in the constructor (int numTriangles, double radius) as (8,1). The variables declared at the top radius and numTriangles should assume those values as my constructor assigns them then runs a calculation. However I get divide by zero error when twoTheta is calculated as numTriangles is zero at this point. Why is this and how can I fix it? Thanks.
package Triangles;
public class Triangles {
double radius;
int numTriangles;
double twoTheta = 360/numTriangles;
double theta = twoTheta / 2;
double base;
double height;
double result;
double halfTriangleArea;
double triangleArea;
double area;
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
runCalculation();
}
// My methods
public double calculateBase() { // SOH
double thetaToRadians = Math.toRadians(theta);
double base = Math.sin(thetaToRadians) / radius;
return base;
}
public double calculateHeight() { // CAH
double thetaToRadians = Math.toRadians(theta);
double height = Math.cos(thetaToRadians) / radius;
return height;
}
public double checkPythag(double base, double height) {
double a = base;
double b = height;
double result = Math.sqrt(a*a + b*b);
return result;
}
public double calculateArea(double base, double height) {
double halfTriangleArea = (0.5) * base * height;
return halfTriangleArea;
}
public double runCalculation() {
base = calculateBase();
height = calculateHeight();
result = checkPythag(base, height);
halfTriangleArea = calculateArea(base, height);
triangleArea = 2 * halfTriangleArea;
// C = Pi * D = Pi * 2 * r
// A = Pi * r.^2
area = numTriangles * triangleArea;
// Substitute Pi for X
// area = X * r.^2
// if r is 1
// area = X
return area;
}
// Runnable
public static void main(String[] args) { // create an instance of class to run in main
Triangles triangles = new Triangles(8, 1);
System.out.println("radius: " + triangles.radius);
System.out.println("numTriangles: " + triangles.numTriangles);
System.out.println("twoTheta " + triangles.twoTheta);
System.out.println("theta " + triangles.theta);
System.out.println("base: " + triangles.base);
System.out.println("height: " + triangles.height);
System.out.println("checkPythag " + triangles.result + " | " + triangles.radius);
System.out.println("halfTriangleArea: " + triangles.halfTriangleArea);
System.out.println("triangleArea: " + triangles.triangleArea);
System.out.println("Approximation of Pi by triangles: " + triangles.area);
}
}
As multiple answers have pointed out, twoTheta (and theta as well) is initialized before constructor is called, hence the error.
I suggest you initialize twoTheta, and theta inside the constructor.
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
//Initialize twoTheta
this.twoTheta = 360/this.numTriangles;
this.theta = this.twoTheta/2;
runCalculation();
}
You call runCalculation() from the constructor - at this moment twoTheta has assigned it's default value (it's 0 for primitives and that default value is assigned even before constructor is called). There are two simple ways of solving your problem:
You should call runCalculation() from outside of the constructor to be sure that all fields are initialized to values other than default (to values that you specified)
OR
You could initialize twoTheta and thetain the constructor before calling runCalculation().
If you want to use first option - change your main method like this to see results that you expect:
public static void main(String[] args) {
Triangles triangles = new Triangles(8, 1);
triangles.runCalculation();
...
}
You should also delete call of runCalculation() from the body of the constructor.
If you choose second way of solving your problem, just initialize theta and twoTheta before runCalculation() in the constructor body:
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
this.twoTheta = 360/this.numTriangles;
this.theta = this.twoTheta/2;
runCalculation();
}
You might want to look here at official Java tutorial to see a list of default values assigned to primitive types and to read a bit more about it (by the way, objects are assigned to null by default).
Ths class attributes are initialized before the constructor is called.
So, the attribute numTriangles is first set to 0. After that double twoTheta = 360/numTriangles; is executed.
The constructor is called afterwards.
That's why you get your error.
Therefore, don't initialize the attributes twoTheta and theta directly but let the constructor handle it after having set the numTriangles and radius attributes.
Call runCalculation();
after
Triangles triangles = new Triangles(8, 1);
in your main method.
Let the constructor complete.
Because these definitions are executed at the creation of the class and not at the instantiation of the object. Furthermore, when you declare but don't assign radius or numTriangles, the default value 0 is used. The default value is 0 for any primitive type (double, int, float, ...) and null for any other type (String, Triangle, ...).
You should only declare them in the class and assign them in the constructor.
double radius;
int numTriangles;
double twoTheta;
public Triangle(double radius, int numTriangles) {
this.radius = radius;
this.numTriangles = numTriangles;
this.twoTheta = 360 / numTriangles;
}
You can change your code like this to avoid the error.
public Triangles(int numTriangles, double radius) {
this.numTriangles = numTriangles;
this.radius = radius;
initialize();
runCalculation();
}
private void initialize()
{
twoTheta = 360/numTriangles;
theta = twoTheta / 2;
}
I am trying to make a program that calculates the area of a triangle given the values for all three sides. When I run my program with my runner file my area comes out to " 0.0"
Here is the classes full code (also I know I did the same code for setSides and triangle but my instructor gave us this shell and I didn't know what to put in there)
import java.util.Scanner;
import java.lang.Math.*;
public class Triangle
{
private int sideA;
private int sideB;
private int sideC;
private double theArea;
private double s;
private double perimeter;
public Triangle()
{
sideA = 1;
sideB = 1;
sideC = 1;
}
public Triangle(int a, int b, int c)
{
sideA = (int) a;
sideB = (int) b;
sideC = (int) c;
}
public void setSides(int a, int b, int c)
{
sideA = (int) a;
sideB = (int) b;
sideC = (int) c;
}
private double calcPerimeter()
{
double perimeter = sideA + sideB + sideC;
return perimeter;
}
private double calcArea()
{
double s = calcPerimeter() / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
public void print()
{
System.out.println("Area == " + theArea);
}
}
I did an system out on your statement. What you are using is not an subtract operator. Please fix that. It will work. Also define the permiter.
System.out.println((int)'–');
output:
8211
Is it possible that you copied some of your source code from a document that isn't a simple text document?
If so, then your problem is that your minus signs are not the proper character. Try re-typing them in a text editor.
ED: Also, a minus sign should be surrounded by spaces. When I first looked at this, it threw me.
In your revised code, you can be square rooting a negative number, which would through you in a really bad state.
Remove:
private double perimeter;
And change:
private double calcArea()
{
double s = perimeter / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
To:
private double calcArea()
{
double s = calcPerimeter() / 2;
double theArea = (Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC)));
return theArea;
}
Here is what is happening. You declare a private double called perimeter. Later in the code you once again declare a double called perimeter. When you do this, things get really confusing! Make sure you only declare variables with the same name ONCE, and reference them thereafter.
In my Java Course, there's an exercise for making a class called Area with 4 overloaded constructors to calculate the area of a circle, a triangle, a rectangle or a cillinder.
After solving 6 errors, I still have 3 left.
This is the code I used:
import java.lang.Math;
class Area {
public double pi = Math.PI;
private int b, l, w, area;
private double r, h;
public Area(){
}
public Area(double radio){
r = radio;
area = pi * r * r;
}
public Area(int base, double alt){
b = base;
h = alt;
double o5 = 0.5;
double db = (double) b;
area = o5 * db * h;
}
public Area(int lar, int anc){
l = lar;
w = anc;
area = l * w;
}
public Area(double radio, double alt){
r = radio;
h = alt;
area = pi * r * r * h;
}
}
public class JavaCLab2P144 {
/**
* #param args
*/
public static void main(String[] args){
Area circ = new Area(4.0);
Area tria = new Area(6,3.0);
Area rect = new Area(2,4);
Area cili = new Area(4.0,10.0);
System.out.println("Area de un circulo:\t" + circ);
System.out.println("Area de un triangulo:\t" + tria);
System.out.println("Area de un rectangulo:\t" + rect);
System.out.println("Area de un cilindro:\t" + cili);
}
}
This is the error I get:
java/JavaCLab2P144/JavaCLab2P144.java:14: error: possible loss of precision
area = pi * r * r;
^
required: int
found: double
java/JavaCLab2P144/JavaCLab2P144.java:22: error: possible loss of precision
area = o5 * db * h;
^
required: int
found: double
java/JavaCLab2P144/JavaCLab2P144.java:34: error: possible loss of precision
area = pi * r * r * h;
^
required: int
found: double
3 errors
You cannot implicitly convert from double to it since you will possibly lose precision as errors indicate. You need an explicit cast to it using cast operator : (int) after assignment operator and becaude of order of ops you should put parens around multiplications like so
Area= (int)(pi * r * r);
There are many other issues to consider in your class such as choice of it for area instead of double since result is a double. As other poster stated you should use double instead for area field. You also don't need to declare variable for pi since it'd already a static cost on math or at least make it private static final
Problem is that double can have values like 1.5 which in case you want to change into int could be 1 or 2 (or is just you're mistake in coding). So java tells you that you have to do something about it.
To solve it you can cast double to int, which cuts to full number
double x = 1.2;
double y = 1.7;
int a = (int) x; // a == 1
int b = (int) y; // b == 1
Other option (in you're case better) is using Math#round(double) function
double x = 1.2;
double y = 1.7;
// Math.round(double) return long, so you also have to cast it into int
int a = (int) Math.round(x); // a == 1
int b = (int) Math.round(y); // b == 2
I can't seem to figure out why my coneVolume method is returning zero when all of my other methods are working properly.
import java.util.Scanner;
public class P56old{
public static double sphereVolume(double r){
double sphereVolume = (4/3)*(Math.PI)*(Math.pow(r, 3));
return sphereVolume;
}
public static double sphereSurface(double r){
double sphereSurface = 4 * (Math.PI) * Math.pow(r, 2);
return sphereSurface;
}
public static double cylinderVolume(double r, double h){
double cylinderVolume = (Math.PI) * (Math.pow(r, 2)) * h;
return cylinderVolume;
}
public static double cylinderSurface(double r, double h){
double cylinderSurface = 2 * (Math.PI) * (Math.pow(r, 2)) + 2 * Math.PI * r * h;
return cylinderSurface;
}
public static double coneVolume(double r, double h){
double coneVolume = (1/3) * Math.PI * (Math.pow(r,2)) * h;
return coneVolume;
}
public static double coneSurface(double r, double h){
double s = Math.sqrt(Math.pow(r,2) + Math.pow(h, 2));
double coneSurface = Math.PI * Math.pow(r,2) + Math.PI * r * s;
return coneSurface;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Please give the radius: ");
double r = in.nextDouble();
System.out.print("Please give the height: ");
double h = in.nextDouble();
double coneVolume = coneVolume(r,h);
double sphereVolume = sphereVolume(r);
double sphereSurface = sphereSurface(r);
double cylinderVolume = cylinderVolume(r,h);
double cylinderSurface = cylinderSurface(r,h);
double coneSurface = coneSurface(r,h);
System.out.println("The Sphere Volume is " + sphereVolume);
System.out.println("The Sphere Surface is " + sphereSurface);
System.out.println("The Cylinder volume is " + cylinderVolume);
System.out.println("The Cylinder Surface is " + cylinderSurface);
System.out.println("The Cone Volume is " + coneVolume);
System.out.println("The Cone Surface is " + coneSurface);
}
}
I'd appreciate any insight on the matter, and any critique is appreciated. I think it may have to do with all the public classes and maybe another method is affecting the coneVolume method but I just don't know enough about methods at the moment to fix the issue at hand.
When you do 1/3, it does integer division, resulting in 0 (the remainder is 1). Multiplying by 0 gives 0. Do 1.0/3.0 instead, and it will correctly compute an approximation to one third.