I had to use an outside class of values to run my main method. My outside class (Circle class) is as follows:
import java.text.DecimalFormat;
public class Circle
{ //start class Circle
private double radius; //stores user input for radius
private int x; //stores user input for x
private int y; //stores user input for y
public Circle()
{ //open Circle()
} //close Circle()
public Circle (double radius)
{ //start Circle
setRadius(radius);
} //end Circle(double)
public Circle (int x, int y)
{ //start Circle
setX(x);
setY(y);
} //end Circle(int, int)
public Circle (double radius, int x, int y)
{ //start Circle
setX(x);
setY(y);
if (radius > 0) //makes sure radius has a correct value
{
this.radius=radius; //stores the input radius if it is positive
}
} // end Circle (double, int, int)
public void setRadius(double radius)
{ //start setRadius
if (radius > 0) //stores correct variable input for radius
{
this.radius=radius;
}
} //end setRadius(double)
public void setX(int x)
{ //start setX
setX(x); //stores X (user input) for x
} //end setX(int)
public void setY(int y)
{ //start setY
setY(y); //stores Y (user input) for y
} //end setY(int)
public void setXY(int x, int y)
{ //start setXY
setXY(x,y); //stores values for X and Y
} //end setXY
public double getRadius()
{ //start getRadius
double dVal; //stores the value for radius
dVal=this.radius; //stores the value for radius for the input circle
return dVal; //returns the value for radius
} //end getRadius()
public int getX()
{ //start getX
return x; //returns the value of x
} //end getX()
public int getY()
{ //starts getY
return y; //returns the value of y
} //ends getY
public double area()
{ //start area()
double dArea; //stores the value of dArea
dArea= radius * radius * 3.141599999; //how dArea is calculated
return dArea; //returns the value stored to dArea
} //end area ()
public double circumference()
{ //start circumference
double dCircum; //stores the value of dCircumference
dCircum= (2* radius) * 3.1415999999; //how dCircumerence is calculated
return dCircum; //returns the calculated value of dCircumference
} //end circumference()
public String toString()
{ //start toString
DecimalFormat df= new DecimalFormat ("0.000");
double dCircum= circumference();
double dArea= area();
String strStuff;
strStuff= "\nRadius: " +this.radius;
strStuff+= "\nXCoord: " + x;
strStuff+= "\nYCoord: " + y;
strStuff+= "\nArea: " + df.format(dArea);
strStuff+="\nCircumference: " + df.format(dCircum);
strStuff+="\n\n";
return strStuff; //returns the values of the class
} //end toString
}
//end Circle class
The following is my TestCircle class
public class TestCircle
{ //start TestCircle
public static void main(String[] args)
{ //starts main
Circle c1= new Circle(7,0,14);
double dRad; //stores a value to dRad
dRad= c1.area(); //runs area() for the stored values
} //ends main
} //ends TestCircle
They both compile correctly but when I run my TestCircle class it just prings this over and over and over "at Circle.setX(Circle.java.44). I'm guessing it has something to do with where I set X on line 44 but I don't know what. Help please.
Your setX method just calls itself, which makes it call itself, then call itself, and so on, until your Java instance runs out of stack space. You need to make setX do something like this.
public void setX(int x){
this.x = x;
}
You will have a similar problem with setY and setXY.
You are calling your setX() method inside in your setX() method. It is a recursive call. Since there is no condition it will run forever and you will get a stack overflow exception
just set passed value to your instance variable inside that method
public void setX(int x){
this.x = x;
}
Related
I have a simple class 2Dpoints with two fields, x and y. I want to write a code so that I could command one point to moves slowly to another point, like so that it moves on the vector line of their distances. But I don't know how?
I've first thought that it should contain a for loop so that it would know, it should move till it reaches the other point
something like for(int d=0 ; d<distance ; d++) but I don't know how should I then command it so that it would move on the line?
import java.lang.Math.*;
public class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x=x;
this.y=y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int distance) {
x = x + distance;
}
public void setY(int distance) {
y = y + distance;
}
public void moveAbout(int dx, int dy) {
x = x + dx;
y = y + dy;
}
/// method for calculating the distance to another point
public double giveDistance(Punkt otherPoint) {
return Math.sqrt(
(otherPoint.getY() - y) *
(otherPoint.getY() - y) +
(otherPoint.getX() - x) *
(otherPoint.getX() - x));
}
}
I've commented the major lines:
import static java.lang.Math.*;
/**
* Immutable structure. Functional way
*/
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Here you are. This is what you want to implement.
* from.moveTo(0.0, to) => from
* from.moveTo(1.0, to) => to
*
* #param by - from 0.0 to 1.0 (from 0% to 100%)
* #param target - move toward target by delta
*/
public Point moveTo(double by, Point target) {
Point delta = target.sub(this);
return add(delta.dot(by));
}
public Point add(Point point) {
return new Point(x + point.x, y + point.y);
}
public Point sub(Point point) {
return new Point(x - point.x, y - point.y);
}
public Point dot(double v) {
return new Point(v * x, v * y);
}
public double dist(Point point) {
return sub(point).len();
}
public double len() {
return sqrt(x * x + y * y);
}
public String toString() {
return x + ":" + y;
}
}
class Main {
public static void main(String[] args) {
Point source = new Point(2, 3);
Point target = new Point(-4, 9);
// You can utilize the cycle or implement kind of timer to animate something
for (int t = 0; t <= 100; t++) {
System.out.println(source.moveTo(0.01 * t, target));
}
}
}
https://replit.com/join/sucvdhpqoa-redneckz
#AlexanderAlexandrov I've change the type of my variables to double accordingly, now in one of my classes I have a method givePoints, which uses Scanner for asking a user how many points he wants and what are the coordinates then it saves them into an array of points with first element being always(0,0).
Another method takes an array of points as parameter and sort them in order of their distances to point(0,0).
These methods work perfectly. The problem is with method hitThepoints.
Here I want to first create the array of points, sort them, and then command my robot to hit all the points. robot is an object of class Robot extends circle, with position of type Point, that at first is at point(0,0)
public void hitThePoints(){
Point[] poi=sortPoints (givePoints()); //Creates a sorted array of points
Point short=new Point(poi[1].getX(),poi[1].getY());
System.out.println(" the nearest point is :");
System.out.println("("+short.getX()+ ","+short.getY()+")");
for(int i=1; i<poi.length;i++){
Point source=robot.position;
Point target=new Point(poi[i].getX(), poi[i].getY());
while(source.getX()!=target.getX() &&
source.getY()!=target.getY()){
robot.bewegeUm((source.moveTo(0.01,target)).getX(),
(source.moveTo(0.01,target)).getY());
if(source.getX()!=target.getX() &&
source.getY()!=target.getY()){break;}
System.out.println(source.getX() +","+ source.getY());
}
}
}
I am currently working on a project and i keep getting error messages. I am stuck and have contacted many people (including my instructor), and I have now turned to you guys.
Here is my code so far.
public class Circle
private int radius = getRadius();
private double area = getArea();
public Circle(int r)
{
r = radius;
}
public int getRadius()
{
return radius;
}
public double getArea(int r)
{
return area = Math.PI * r * r;
}
}
/
java.util.Scanner;
public class CircleTest
{
public CircleTest()
{
int radius = getRadius();
double area = getArea(r);
}
public static void main (String[] args)
{
Scanner kboard = new Scanner(System.in);
System.out.print("Give the radius of a circle. ");
String area = kboard.nextLine();
System.out.println("The area of the circle is... " +
area);
System.out.println();
kboard.close();
}
}
C:\Users\jthom\My Work\Circle\src\CircleTest.java:18: error: cannot find symbol
double area = getArea(r);
symbol: variable r
location: class CircleTest
.
C:\Users\jthom\My Work\Circle\src\CircleTest.java:33: error: cannot find symbol
System.out.println("The area of the circle is... " + area);
symbol: variable area
location: class CircleTest
2 errors
Let's start with class Circle. This is your original code:
public class Circle
private int radius = getRadius();
private double area = getArea();
public Circle(int r)
{
r = radius;
}
public int getRadius()
{
return radius;
}
public double getArea(int r)
{
return area = Math.PI * r * r;
}
}
For your variables, you don't need "area", as it is calculated. Also, you shouldn't be assigning radius to anything except in the constructor:
private int radius;
//private double area = getArea(); <-- don't need this variable at all
You pass in "r" to the constructor, but then incorrectly try to assign the "radius" value to it. This is backwards; you should be assigning the "r" value to "radius" instead:
public Circle(int r)
{
radius = r;
}
Finally, in getArea(), you don't need the radius passed in, or "area"; just return the calculated value (using the stored value in "radius", not "r"):
public double getArea()
{
return Math.PI * radius * radius;
}
Put all together, your Circle class should look more like:
public class Circle
private int radius;
public Circle(int r)
{
radius = r;
}
public int getRadius()
{
return radius;
}
public double getArea()
{
return Math.PI * radius * radius;
}
}
Over in CircleTest, you should first get the radius from the user, then pass that to the constructor of Circle. Finally, with your instance of Circle, call its getRadius() and getArea() methods.
You have not defined variable r and area ,to help solve this
replace double area = getArea(r); to double area = circle.getArea(radius);
and
System.out.println("The area of the circle is... " + area); with System.out.println("The area of the circle is... " + circle.getArea(Integer.parseInt(area)));
here the circle is an object of Class circle
Circle circle = new Circle(radius) //Note: circle cannot be accessed from main function create another object for class circle again in main
it should help
edit: here is link about the error What does a "Cannot find symbol" compilation error mean?
I am trying to write a code that follows certain criteria regarding Regular Polygons and finding the perimeter and area of the polygon. I have to write three different classes Point2D, RegularPolygon, and Driver. I can get all of the necessary criteria to work fine except for when it comes to using the instance variable center to have the center coordinates x and y. There are two things that use the center in the RegularPolygon code and I can't get them to work. I need to have a Point2D instance variable center that stores the x and y coordinates of the polygon’s center, with default values 0 for both the x and y components of the Point2D object. I also need to have a constructor that creates a regular polygon with the specified number of sides, length of side, and a Point2D object that represents the center of the polygon, in that order. I also need to have A method public String toString()that returns a String representation of the polygon containing the number of sides, side length and center coordinates for this polygon. Call the toString()method on the Point2Dcenter as part of this method. However, when I go to call the toString method in Point2D it comes up as an error. If anyone can help me figure out why I can't get it to work in my code I would greatly appreciate it.
//Code for Point2D
public class Point2D
{
//Instance Variables
private int x;
private int y;
/**
* Constructor for objects of class Point2D, this will initialize
* the instance variables
*/
public Point2D(int xVariable, int yVariable)
{
//Initializes Instance Variables
x = xVariable;
y = yVariable;
}
//Accessor Method for X variable
public int getX() {
return x;
}
//Accessor Method for X variable
public int getY() {
return y;
}
//ToString Method
public String toString() {
return "<" + x + "," + y + ">";
}
//Method that tests if the values of x and y are equal
public boolean equal(Object o) {
if (o instanceof Point2D) {
Point2D c = (Point2D)o;
}
return false;
}
}
//Code for RegularPolygon
public class RegularPolygon
{
// instance variables
private int n; //Number of sides
private double side; //Length of sides
private double x; //Value of X-Coordinate
private double y; //Value of y-Coordinate
private double center;
/**
* No argument constuctor that creates a regular polygon with
* default values
*/
public RegularPolygon()
{
//Intilializes Instance Variables
n=3;
side =1;
x=0;
y=0;
}
/**
* Constructor that creates a regular polygon with a specific number
* of sides, length of side, and a Point2D object that represents the
* center of the polygon.
*/
public RegularPolygon(int n, double side, double x, double y) {
this.n = n;
this.side= side;
this.x = 0;
this.y = 0;
}
//Mututator Methods
public void setN(int nValue) {
n = nValue;
}
public void setSide(double sideValue) {
side = sideValue;
}
public void setX(double xValue) {
x = xValue;
}
public void setY(double yValue) {
y = yValue;
}
//Accessor Methods
public int getN() {
return n;
}
public double getSide() {
return side;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
//Calculates the Perimeter of the regular polygon
public double getPerimeter() {
return n * side;
}
//Calculates the Area of the regular polygon
public double getArea() {
double area = (n * (Math.pow(side,2))) / (4 * (Math.tan(Math.PI/n)));
return area;
}
//To String Method
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+Point2D.toString(x,y);
}
}
Your toString method in Point2D does not take variables as parameters, yet you call it from RegularPolygon with parameters at the end. But the way you called Point2D uses its toString method like a static method, even though it's not. So you either have to instantiate a Point2D, or make Point2D's toString method static. But the problem with this is that then you have to make your x and y in Point2D static as well. Another problem with making your toString() method static is that you can't override Object's toString method. So I recommend that you do the following:
public String toString() {
return "Number of sides: " + n + ", Side Length: " + side + ", Center Coordinates: "+new Point2D((int)x, (int)y).toString();
}
This is my test class,
public class Shape2DTester {
public static void main(String[] args) {
GeometricObject2D geoObject1 = new ComparableCircle2D(0, 5, 2);
GeometricObject2D geoObject3 = new ComparableCircle2D(0, 0, 2);
System.out.println("geoObject1 overlaps geoObject3: "
+ geoObject1.intersect(geoObject3));
}
}
This is my circle class,
public class ComparableCircle2D extends GeometricObject2D<ComparableCircle2D> {
public double x, y;
public double radius;
ComparableCircle2D() {
super();
this.radius = 1.0;
}
ComparableCircle2D(double radius) {
super();
this.radius = Math.abs(radius);
}
ComparableCircle2D(double x, double y, double radius) {
super(x, y);
this.radius = Math.abs(radius);
}
public double getArea() {
return Math.PI * getRadius() * getRadius();
}
public double getPerimeter() {
return 2 * Math.PI * getRadius();
}
public void setRadius(double setRadius) {
this.radius = Math.abs(setRadius);
}
public double getRadius() {
return radius;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
#Override
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - getX();
double dy = other.y - getY();
double radi = other.radius + getRadius();
return (dx * dx + dy * dy < radi * radi);
}
}
}
this is my superclass,
public abstract class GeometricObject2D<T extends GeometricObject2D> implements
Comparable<GeometricObject2D> {
public double x, y;
GeometricObject2D() {
this.x = 0;
this.y = 0;
}
GeometricObject2D(double x, double y) {
this.x = x;
this.y = y;
}
public abstract double getArea();
public abstract double getPerimeter();
public abstract boolean intersect(GeometricObject2D g);
#Override
public int compareTo(GeometricObject2D o) {
// TODO Auto-generated method stub
return 0;
}
}
I want to find out possibility of intersecting two circles but there is an error in my code that I didn't realize.
For example I create two circle object coordinates-1(0,0) , radius-1=2 and coordinates-2(0,5) ,radius-2=2. That above method must return false but returns true. I didn't find error.
System.out.println("geoObject1 intersects geoObject3: "
+ geoObject1.intersect(geoObject3));
prints geoObject1 intersects geoObject3: true
As #Pshemo said, your code (now that you've shown it) has an extra } at the end that shouldn't be there.
How, if we paste all that code into IDEONE, and run it, we confirm your error.
If we then DEBUG the code by adding a single print statement, we see:
dx=0.0, dy=0.0, radi=4.0
Hmmm, why is dy = 0 when it should be 5?
Answer: Because you added another set of x and y fields to your subclass, that is hiding the fields from the base class!!!!
Simple debugging would have shown you this yourself. This is what #PeterLawrey was talking about in his comment:
you mistake is it is likely to be; the values are not what you think they are. This is where debugging your code can show this.
Of course, if you had used a good IDE, you wouldn't even need to debug, because the IDE would have warned you about the field hiding.
Rather than Math.pow(x, 2) it is more efficient to do x * x, and instead of using Math.sqrt you can square the sum of the radii.
public boolean intersect(GeometricObject2D g) {
ComparableCircle2D other = (ComparableCircle2D) g;
double dx = other.x - x; // e.g. 0 - 0
double dy = other.y - y; // e.g. 5 - 0
double radii = other.radius + radius; // e.g. 2 + 2
return dx * dx + dy * dy < radii * radii ; // e.g. 0 + 25 < 16 is false.
}
You never assign the fields x and y. Therefore dx = dy = 0.
You have to either assign the field's values or use the fields in the superclass (but you shouldn't have fields with the same information in the same object, so remove the fields created in ComparableCircle2D).
Also if your circle is defined as contour, not as area, then the test for intercepting circles is incorrect. Consider the case where 2 circles with the same center have different radii: dx² + dy² = 0 < dr², but the contours don't intersect; only the areas inside the circles overlap.
So, I have a twoparter question. The first part I did, which was creating an interface and then utilizing that interface in two different classes. However the second part of the question has me stumped. I'm not understanding the logic aspect of it. It feels as though the question order should be in reverse. This is two things I need to do to finish up the last portion of the assignment. If anyone here could give me just some tiny guidance as to to the direction I should be taking I'd greatly appreciate it.
Part II:
(1)Create an array of Calculatable objects in main and call the sumCalculate method.
For the most part I understand this, I already began doing it but decided to start working on (2) since that was way more difficult for me. It's basically creating an array of Calculatable objects of a certain size ( I chose 5) and populating it with different calculatable objects ( could be rectangles or squares in my example). But the second half of this question confuses me? Am I calling the sumCalculate method that I'm GOING to be making in question 2? Or am I calling it before I even make the (2) method.
(2)Make a method that accepts an array of Calculatable objects and sums up the values that are returned by each object's call to calculate.
What I'm trying to figure out here in question (2) is this. When it asks me to make the method? Does this mean that I'm making a new method in interface called sumCalc for example, that has parameters that accepts an array of calculatable objects? And then as far as summing up the values that are returned. I'd assume that I'd be adding the calculation double that is returned by calculate methods.
I'd ask my professor but this professor I decided to take has made it a habit of being excessively difficult to reach. Sorry to bother you guys with what is most likely an elementary and not difficult question.
interface Calculatable {
public double calculate(int x);
}
class square implements Calculatable {
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
public static void main(String [] args){
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
}
}
I would create sumCalculate beside main method and be over with it. Lesson is to implement an interface method and use it too.
And beside that I suggest reading Java naming convention and correcting your code accordingly.
The way I understand it you should not change the Interface, especially if the Interface was provided to you!
Just write your sumCalculate below your main method like this
private static double sumCalculate(Calculateable[] c) {
// do your sum up and return the result
}
and call it in your main method like this
double sum = sumCalculate(perimetersums);
few confusion is in my mind.. In the implementation rectangle your are not using the x in the calculate method. I changed the whole class structure a little bit.. Please look.. I think it will help you...
public interface Calculatable {
public double calculate(int x);
public double getPerimeter();
}
public class square implements Calculatable {
public double side;
private double perimeter;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate(int x) {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class rectangle implements Calculatable {
public double length;
public double width;
private double perimeter;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate(int x) {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
this.perimeter=calculation;
return calculation;
}
#Override
public double getPerimeter() {
// TODO Auto-generated method stub
return perimeter;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = perimeter1; //new rectangle(20.5 , 50);
perimetersums[1] = perimeter2;// new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
sum=sum+cal.getPerimeter();
}
return sum;
}
}
I changed the class structure a little bit...
public interface Calculatable {
public double calculate();
}
public class square implements Calculatable {
private final int x=2;
public double side;
square(double side){
this.side = side;
}
public double getside(){
return side;
}
public double calculate() {
double perimeter = side * 4;
System.out.println("This calculate method will output the perimeter divided by the parameter x");
double calculation = perimeter / x;
System.out.println("The original perimeter was " + perimeter + ". And the calculated perimeter is " + calculation +".");
return calculation;
}
}
public class rectangle implements Calculatable {
private final int x=5;
public double length;
public double width;
rectangle(double length , double width){
this.length = length;
this.width = width;
}
public double getlength(){
return length;
}
public double getwidth(){
return width;
}
public double calculate() {
double perimeter = 2 * (length + width);
double calculation = 2 * perimeter;
System.out.println("This will return the perimeter of the rectangle times the x paramater");
System.out.println("Your current perimeter is " + perimeter + " and your perimeter after the calculation is " + calculation + ".");
return calculation;
}
}
public class MainMethod {
public static void main(String[] args) {
Calculatable perimeter1 = new rectangle(20.5 , 50);
// perimeter1.calculate(5);
Calculatable perimeter2 = new square(10.5);
//perimeter2.calculate(2);
Calculatable[] perimetersums = new Calculatable[5];
perimetersums[0] = new rectangle(20.5 , 50);
perimetersums[1] = new rectangle(10 , 25);
System.out.println("the sum is= "+sumCalculate(perimetersums));
}
private static double sumCalculate ( Calculatable[] perimetersums)
{
double sum=0.0;
for(int i=0;i<perimetersums.length;i++)
{
Calculatable cal=perimetersums[i];
if(cal!=null)
{
sum=sum+cal.calculate();
}
}
return sum;
}
}