I'm trying to find the area of a Polygon using the following formula:
Area = r^2 n sin( 2 π / n) / 2
where n is the number of sides and r is the radius. I do not think my code is producing the correct result. If n= 6 and r = 4, i'm getting an area of 24. My code is as follows:
import java.math.*;
public class RegularPolygon {
private int n; // number of vertices
private double r; //radius of the polygon
/**
* This is the full constructor
* #param n is the number of vertices
* #param r is the radius
*/
public RegularPolygon(int n, double r) {
super();
this.n = n;
this.r = r;
}
/**
* default constructor. Sets number of sides and radius to zero
*/
public RegularPolygon() {
super();
this.n = 0;
this.r = 0;
}
//getters and setters for Number of vertices "n" and radius "r".
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
#Override
public String toString() {
return "RegularPolygon [n=" + n + ", r=" + r + "]";
}
public double area(){
float area;
//this method returns the area of the polygon
//Use Math.PI and Math.sin as needed
return area = (float) (Math.pow(r, 2)* n * ( Math.sin(Math.PI / n)/2));
It is unclear to me where my order of operations is messed up.
You're not translating the formula correctly. You need return Math.pow(r, 2) * n * Math.sin(2 * Math.PI / n) / 2; As forpas pointed out in the comments, you're missing a 2 and saying Math.sin(Math.PI / n) This has nothing to do with order of operations, since it's all just multiplication and division.
You should not type cast to float as you have declared the return type of the method as double
return Math.pow(r,2) * n * Math.sin(2 * Math.PI/n) / 2;
I think the above code will satisfy your need.
I am attempting to use the slopeTo method inside my slopeCompare subclass in my comparator definition. However I get an error in eclipse telling me to change slopeTo to a static method. It also does not work when I use this.slopeTo(). I thought that the whole point of subclasses was that they can use all the methods of the superclass. Can someone help me clarify what I am not understanding here? I apologize if I am misusing terminology but comparators are a new topic and I am not entirely comfortable with them.
(this is from the princeton algorithms course on udacity)
import java.util.Comparator;
import edu.princeton.cs.algs4.StdDraw;
public class Point implements Comparable<Point> {
private final int x; // x-coordinate of this point
private final int y; // y-coordinate of this point
/**
* Initializes a new point.
*
* #param x the <em>x</em>-coordinate of the point
* #param y the <em>y</em>-coordinate of the point
*/
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
/**
* Draws this point to standard draw.
*/
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
/**
* Draws the line segment between this point and the specified point
* to standard draw.
*
* #param that the other point
*/
public void drawTo(Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
/**
* Returns the slope between this point and the specified point.
* Formally, if the two points are (x0, y0) and (x1, y1), then the slope
* is (y1 - y0) / (x1 - x0). For completeness, the slope is defined to be
* +0.0 if the line segment connecting the two points is horizontal;
* Double.POSITIVE_INFINITY if the line segment is vertical;
* and Double.NEGATIVE_INFINITY if (x0, y0) and (x1, y1) are equal.
*
* #param that the other point
* #return the slope between this point and the specified point
*/
public double slopeTo(Point that) {
/* YOUR CODE HERE */
if (this.compareTo(that) == 0){
return Double.NEGATIVE_INFINITY;
}
double slope = (double)(that.y-this.y)/(that.x-this.x);
return slope;
}
/**
* Compares two points by y-coordinate, breaking ties by x-coordinate.
* Formally, the invoking point (x0, y0) is less than the argument point
* (x1, y1) if and only if either y0 < y1 or if y0 = y1 and x0 < x1.
*
* #param that the other point
* #return the value <tt>0</tt> if this point is equal to the argument
* point (x0 = x1 and y0 = y1);
* a negative integer if this point is less than the argument
* point; and a positive integer if this point is greater than the
* argument point
*/
public int compareTo(Point that) {
if (this.y > that.y){
return 1;
}
if (this.y < that.y){
return -1;
}
if ((this.y == that.y) && (this.x < that.x)){
return -1;
}
if ((this.y == that.y) && (this.x > that.x)){
return 1;
}
else {
return 0;
}
}
/**
* Compares two points by the slope they make with this point.
* The slope is defined as in the slopeTo() method.
*
* #return the Comparator that defines this ordering on points
*/
public Comparator<Point> slopeOrder() {
/* YOUR CODE HERE */
return new SlopeCompare();
}
private static class SlopeCompare implements Comparator<Point> {
public int compare(Point a, Point b){
if (slopeTo(a) < slopeTo(b)){
return -1;
}
return 0;
}
}
/**
* Returns a string representation of this point.
* This method is provide for debugging;
* your program should not rely on the format of the string representation.
*
* #return a string representation of this point
*/
public String toString() {
/* DO NOT MODIFY */
return "(" + x + ", " + y + ")";
}
/**
* Unit tests the Point data type.
*/
public static void main(String[] args) {
/* YOUR CODE HERE */
}
}
Sorry I can't comment yet.
But yes, you cannot call non static method inside static method.
Static belongs to class and non-static belongs to the instance you can look more into that in google.
If SlopeCompare should be static you need to have an instance of Point to call slopeTo.
this in this.slopeTo() represents SlopeCompare instance, inner class can indeed access fields and methods of outer class, but it's not inherit, so you can not access slopeTo() with this keywords, you can ues outer.this to get an instance of the outer class.
Two solutions for references:
1.define slopeTo() method with static:
public static double slopeTo(Point that) {
2.remove the static keywords from the member class:
private class SlopeCompare implements Comparator<Point> {
Problem: Did I properly make this UML Diagram?
UML Diagram:
Circle
-radius : double
+PI : double
+setRadius(rad: double) : void
+getRadius(rad: double) : void
+getArea() : double
+getDiameter() : double
+getCircumference() : double
Code:
public class Circle
{
//Declaration
private double radius;
public static final double PI = 3.14159;
public Circle()
{
radius = 0.0;
}
public Circle(double rad)
{
radius = rad;
}
/**
The setRadius method stores a value in the
radius field.
#param rad The value to store in radius.
*/
public void setRadius(double rad)
{
radius = rad;
}
/**
The getRadius method returns a Radius
for the Circle.
#return The entered radius in the radius field.
*/
public double getRadius(double rad)
{
return radius;
}
/**
The getArea method returns an Area
for the Circle.
#return The Area for the Circle.
*/
public double getArea()
{
return PI * (radius * radius);
}
/**
The getDiameter method returns a diameter
for the Circle.
#return The diameter for the Circle.
*/
I wrote a Rectangle class that has length and width for the fields. setLength, setWidth, getLength, getWidth, getPerimeter, and getArea for the methods. In my main program, RectangleTest; when I run it; I am able to enter in the length and width. The program then displays the value that I entered in for length (which is correct), but when it displays the value that I entered in for width; it always displays 0.0. Please help. Here is the source code:
package com.delgado;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class RectangleTest {
public static void main(String[] args) {
double length;
double width;
String input;
DecimalFormat formatter = new DecimalFormat("#0.0");
input = JOptionPane
.showInputDialog("Please enter the length of the basketball court: ");
length = Double.parseDouble(input);
input = JOptionPane
.showInputDialog("Please enter the width of the basketball court: ");
width = Double.parseDouble(input);
Rectangle basketBall = new Rectangle(length, width);
JOptionPane.showMessageDialog(
null,
"You entered " + formatter.format(basketBall.getLength())
+ " for the length, and "
+ formatter.format(basketBall.getWidth())
+ " for the width.");
}
}
If you need the source code for the Rectangle class, please let me know. Thank you guys.
Here is the source code for the Rectangle class:
package com.delgado;
/* This Class creates an object that takes the length and width as arguments,
* and returns the perimeter and area of a rectangle.
*/
public class Rectangle {
private double length; // Holds the length.
private double width; // Holds the width.
/**
* This is a default constructor
*/
public Rectangle() {
}
/**
* This is a constructor that takes two arguments; len and w.
*
* #param len
* The length of the rectangle.
* #param w
* The width of the rectangle.
*/
public Rectangle(double len, double w) {
length = len;
w = width;
}
/**
* The method setLength sets the length of a rectangle.
*
* #param len
* The length of a rectangle.
*/
public void setLength(double len) {
length = len;
}
/**
* The method setWidth sets the width of a rectangle.
*
* #param w
* The width of a rectangle.
*/
public void setWidth(double w) {
width = w;
}
/**
* The method getLength returns the length of a rectangle.
*
* #return Returns the length of a rectangle.
*/
public double getLength() {
return length;
}
/**
* The method getWidth returns the width of a rectangle.
*
* #return Returns the width of a rectangle.
*/
public double getWidth() {
return width;
}
/**
* The method getArea returns the area of a rectangle.
*
* #return Returns the area of a rectangle.
*/
public double getArea() {
return length * width;
}
/**
* The method getPerimeter returns the perimeter of a rectangle.
*
* #return Returns the perimeter of a rectangle.
*/
public double getPerimeter() {
return (length * 2) + (width * 2);
}
}
I have to wonder if your JOptionPane is messing with your Scanner... can't tell til I test it, but regardless, I would simplify things even further. As long as you're showing JOptionPanes, who not show one that displays a message and gets input at the same time?
JOptionPane.showInputDialog(....)
Edit: Yikes
public Rectangle(double len, double w) {
length = len;
w = width;
}
You're setting the w parameter here, not the width field!!! Instead it should be:
width = w; //*********
Do you understand why?
I been trying to figure out how to set up this equation to add two complex numbers for Java.
There's two methods, but I don't understand exactly what the first one is asking me to do. Is it saying I need to do (real1 + imag1) instead of (real1 + real2)? If that is the case then how would I get that result to go into c1? I also am having trouble with the second method result to hold the sum and return it.
/*Method for adding the real and imaginary parts of two complex numbers,
*which returns the result in a new complex number
*/
public static ComplexNumber addComplexNumbers(double real1, double imag1, double real2, double imag2){
ComplexNumber result = ComplexNumber.addComplexNumbers(real1, imag1, real2, imag2);
result.setReal(real1 + real2);
result.setImag(imag1 + imag2);
return result;
}
//Method for adding two complex numbers
public static ComplexNumber addComplexNumbers(ComplexNumber c1, ComplexNumber c2){
ComplexNumber result = new ComplexNumber();
result = (c1.real + c2.real) + (c1.imag + c2.imag);
}
final public class Complex {
private final double real;
private final double imag;
public Complex() {
this(0.0, 0.0);
}
public Complex(double r) {
this(r, 0.0);
}
public Complex(double r, double i) {
this.real = r;
this.imag = i;
}
public Complex add(Complex addend) {
return new Complex((this.real + addend.real), (this.imag + addend.imag));
}
}
Though this already been answered I thought people may benefit by the following class which does a lot of functions related to Complex Numbers.
This has been released under MIT License and the GitHub project is here.
/**
* <code>ComplexNumber</code> is a class which implements complex numbers in Java.
* It includes basic operations that can be performed on complex numbers such as,
* addition, subtraction, multiplication, conjugate, modulus and squaring.
* The data type for Complex Numbers.
* <br /><br />
* The features of this library include:<br />
* <ul>
* <li>Arithmetic Operations (addition, subtraction, multiplication, division)</li>
* <li>Complex Specific Operations - Conjugate, Inverse, Absolute/Magnitude, Argument/Phase</li>
* <li>Trigonometric Operations - sin, cos, tan, cot, sec, cosec</li>
* <li>Mathematical Functions - exp</li>
* <li>Complex Parsing of type x+yi</li>
* </ul>
*
* #author Abdul Fatir
* #version 1.1
*
*/
public class ComplexNumber
{
/**
* Used in <code>format(int)</code> to format the complex number as x+yi
*/
public static final int XY = 0;
/**
* Used in <code>format(int)</code> to format the complex number as R.cis(theta), where theta is arg(z)
*/
public static final int RCIS = 1;
/**
* The real, Re(z), part of the <code>ComplexNumber</code>.
*/
private double real;
/**
* The imaginary, Im(z), part of the <code>ComplexNumber</code>.
*/
private double imaginary;
/**
* Constructs a new <code>ComplexNumber</code> object with both real and imaginary parts 0 (z = 0 + 0i).
*/
public ComplexNumber()
{
real = 0.0;
imaginary = 0.0;
}
/**
* Constructs a new <code>ComplexNumber</code> object.
* #param real the real part, Re(z), of the complex number
* #param imaginary the imaginary part, Im(z), of the complex number
*/
public ComplexNumber(double real, double imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
/**
* Adds another <code>ComplexNumber</code> to the current complex number.
* #param z the complex number to be added to the current complex number
*/
public void add(ComplexNumber z)
{
set(add(this,z));
}
/**
* Subtracts another <code>ComplexNumber</code> from the current complex number.
* #param z the complex number to be subtracted from the current complex number
*/
public void subtract(ComplexNumber z)
{
set(subtract(this,z));
}
/**
* Multiplies another <code>ComplexNumber</code> to the current complex number.
* #param z the complex number to be multiplied to the current complex number
*/
public void multiply(ComplexNumber z)
{
set(multiply(this,z));
}
/**
* Divides the current <code>ComplexNumber</code> by another <code>ComplexNumber</code>.
* #param z the divisor
*/
public void divide(ComplexNumber z)
{
set(divide(this,z));
}
/**
* Sets the value of current complex number to the passed complex number.
* #param z the complex number
*/
public void set(ComplexNumber z)
{
this.real = z.real;
this.imaginary = z.imaginary;
}
/**
* Adds two <code>ComplexNumber</code>.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 + z2).
*/
public static ComplexNumber add(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real + z2.real, z1.imaginary + z2.imaginary);
}
/**
* Subtracts one <code>ComplexNumber</code> from another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 - z2).
*/
public static ComplexNumber subtract(ComplexNumber z1, ComplexNumber z2)
{
return new ComplexNumber(z1.real - z2.real, z1.imaginary - z2.imaginary);
}
/**
* Multiplies one <code>ComplexNumber</code> to another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 * z2).
*/
public static ComplexNumber multiply(ComplexNumber z1, ComplexNumber z2)
{
double _real = z1.real*z2.real - z1.imaginary*z2.imaginary;
double _imaginary = z1.real*z2.imaginary + z1.imaginary*z2.real;
return new ComplexNumber(_real,_imaginary);
}
/**
* Divides one <code>ComplexNumber</code> by another.
* #param z1 the first <code>ComplexNumber</code>.
* #param z2 the second <code>ComplexNumber</code>.
* #return the resultant <code>ComplexNumber</code> (z1 / z2).
*/
public static ComplexNumber divide(ComplexNumber z1, ComplexNumber z2)
{
ComplexNumber output = multiply(z1,z2.conjugate());
double div = Math.pow(z2.mod(),2);
return new ComplexNumber(output.real/div,output.imaginary/div);
}
/**
* The complex conjugate of the current complex number.
* #return a <code>ComplexNumber</code> object which is the conjugate of the current complex number
*/
public ComplexNumber conjugate()
{
return new ComplexNumber(this.real,-this.imaginary);
}
/**
* The modulus, magnitude or the absolute value of current complex number.
* #return the magnitude or modulus of current complex number
*/
public double mod()
{
return Math.sqrt(Math.pow(this.real,2) + Math.pow(this.imaginary,2));
}
/**
* The square of the current complex number.
* #return a <code>ComplexNumber</code> which is the square of the current complex number.
*/
public ComplexNumber square()
{
double _real = this.real*this.real - this.imaginary*this.imaginary;
double _imaginary = 2*this.real*this.imaginary;
return new ComplexNumber(_real,_imaginary);
}
/**
* #return the complex number in x + yi format
*/
#Override
public String toString()
{
String re = this.real+"";
String im = "";
if(this.imaginary < 0)
im = this.imaginary+"i";
else
im = "+"+this.imaginary+"i";
return re+im;
}
/**
* Calculates the exponential of the <code>ComplexNumber</code>
* #param z The input complex number
* #return a <code>ComplexNumber</code> which is e^(input z)
*/
public static ComplexNumber exp(ComplexNumber z)
{
double a = z.real;
double b = z.imaginary;
double r = Math.exp(a);
a = r*Math.cos(b);
b = r*Math.sin(b);
return new ComplexNumber(a,b);
}
/**
* Calculates the <code>ComplexNumber</code> to the passed integer power.
* #param z The input complex number
* #param power The power.
* #return a <code>ComplexNumber</code> which is (z)^power
*/
public static ComplexNumber pow(ComplexNumber z, int power)
{
ComplexNumber output = new ComplexNumber(z.getRe(),z.getIm());
for(int i = 1; i < power; i++)
{
double _real = output.real*z.real - output.imaginary*z.imaginary;
double _imaginary = output.real*z.imaginary + output.imaginary*z.real;
output = new ComplexNumber(_real,_imaginary);
}
return output;
}
/**
* Calculates the sine of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the sine of z.
*/
public static ComplexNumber sin(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.sin(z.real) * (x + x_inv)/2;
double i = Math.cos(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the cosine of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the cosine of z.
*/
public static ComplexNumber cos(ComplexNumber z)
{
double x = Math.exp(z.imaginary);
double x_inv = 1/x;
double r = Math.cos(z.real) * (x + x_inv)/2;
double i = -Math.sin(z.real) * (x - x_inv)/2;
return new ComplexNumber(r,i);
}
/**
* Calculates the tangent of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the tangent of z.
*/
public static ComplexNumber tan(ComplexNumber z)
{
return divide(sin(z),cos(z));
}
/**
* Calculates the co-tangent of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the co-tangent of z.
*/
public static ComplexNumber cot(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),tan(z));
}
/**
* Calculates the secant of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the secant of z.
*/
public static ComplexNumber sec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),cos(z));
}
/**
* Calculates the co-secant of the <code>ComplexNumber</code>
* #param z the input complex number
* #return a <code>ComplexNumber</code> which is the co-secant of z.
*/
public static ComplexNumber cosec(ComplexNumber z)
{
return divide(new ComplexNumber(1,0),sin(z));
}
/**
* The real part of <code>ComplexNumber</code>
* #return the real part of the complex number
*/
public double getRe()
{
return this.real;
}
/**
* The imaginary part of <code>ComplexNumber</code>
* #return the imaginary part of the complex number
*/
public double getIm()
{
return this.imaginary;
}
/**
* The argument/phase of the current complex number.
* #return arg(z) - the argument of current complex number
*/
public double getArg()
{
return Math.atan2(imaginary,real);
}
/**
* Parses the <code>String</code> as a <code>ComplexNumber</code> of type x+yi.
* #param s the input complex number as string
* #return a <code>ComplexNumber</code> which is represented by the string.
*/
public static ComplexNumber parseComplex(String s)
{
s = s.replaceAll(" ","");
ComplexNumber parsed = null;
if(s.contains(String.valueOf("+")) || (s.contains(String.valueOf("-")) && s.lastIndexOf('-') > 0))
{
String re = "";
String im = "";
s = s.replaceAll("i","");
s = s.replaceAll("I","");
if(s.indexOf('+') > 0)
{
re = s.substring(0,s.indexOf('+'));
im = s.substring(s.indexOf('+')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),Double.parseDouble(im));
}
else if(s.lastIndexOf('-') > 0)
{
re = s.substring(0,s.lastIndexOf('-'));
im = s.substring(s.lastIndexOf('-')+1,s.length());
parsed = new ComplexNumber(Double.parseDouble(re),-Double.parseDouble(im));
}
}
else
{
// Pure imaginary number
if(s.endsWith("i") || s.endsWith("I"))
{
s = s.replaceAll("i","");
s = s.replaceAll("I","");
parsed = new ComplexNumber(0, Double.parseDouble(s));
}
// Pure real number
else
{
parsed = new ComplexNumber(Double.parseDouble(s),0);
}
}
return parsed;
}
/**
* Checks if the passed <code>ComplexNumber</code> is equal to the current.
* #param z the complex number to be checked
* #return true if they are equal, false otherwise
*/
#Override
public final boolean equals(Object z)
{
if (!(z instanceof ComplexNumber))
return false;
ComplexNumber a = (ComplexNumber) z;
return (real == a.real) && (imaginary == a.imaginary);
}
/**
* The inverse/reciprocal of the complex number.
* #return the reciprocal of current complex number.
*/
public ComplexNumber inverse()
{
return divide(new ComplexNumber(1,0),this);
}
/**
* Formats the Complex number as x+yi or r.cis(theta)
* #param format_id the format ID <code>ComplexNumber.XY</code> or <code>ComplexNumber.RCIS</code>.
* #return a string representation of the complex number
* #throws IllegalArgumentException if the format_id does not match.
*/
public String format(int format_id) throws IllegalArgumentException
{
String out = "";
if(format_id == XY)
out = toString();
else if(format_id == RCIS)
{
out = mod()+" cis("+getArg()+")";
}
else
{
throw new IllegalArgumentException("Unknown Complex Number format.");
}
return out;
}
}
Check out this simple program .
class Com{
int real,img;
Com (int r, int i){
real = r;
img = i;
}
void add(Com c){
real = real + c.real;
img = img + c.img;
}
void print(){
System.out.println(real+" +i"+img);
}
}
public class complex {
public static void main(String [] args){
Com c1 = new Com(10,20);
c1.print();
Com c2 = new Com(20,10);
c1.add(c2);
c1.print();
}
}