Before you read ahead this question is for my homework so it will be specific.
I am writing some code that uses polymorphism to display the properties of a rectangle (ie, x, y, height...). The code uses inheritance and polymorphism to achieve the results. Everything like the width and topleftX point is being determined using an algorithm that picks a random integer from a specified range. How I tried to fix the problem is to write a getWidth() and getLength() method to the rectangle class. I put in a super(); for the other class that gets the X and Y coordinates.
The problem that I am having is that I am unsure of how to access the classes that will give me the width and height of the rectangle. Inside of the methods that I have written the super() displays an error and it says "(x,y) cannot be applied to ()" which I am unsure of what it means. I assume that the values are private and I cannot access them, but in the class with the implementation, there are no private instances, so I am confused.
This is my code below:
public GeometricShapeTester(){
shapes = new GeometricShape[20];
Random rand = new Random();
int option;
final int COORD = 50;
final int LENGTH1 = 50;
final int LENGTH2 = 100;
for(int i=0; i<shapes.length; i++){
option=rand.nextInt(4);
switch(option){
case 0:
shapes[i]= new Rectangle(
rand.nextInt(COORD),
rand.nextInt(COORD),
rand.nextInt(LENGTH2),
rand.nextInt(LENGTH2));
break;
case 1:
shapes[i]= new Square(
rand.nextInt(COORD),
rand.nextInt(COORD),
rand.nextInt(LENGTH2));
break;
case 2:
shapes[i]= new Oval(
rand.nextInt(COORD),
rand.nextInt(COORD),
rand.nextInt(LENGTH1),
rand.nextInt(LENGTH2));
break;
case 3:
shapes[i]= new Circle(
rand.nextInt(COORD),
rand.nextInt(COORD),
rand.nextInt(LENGTH1));
}
}
}
public GeometricShape[] getShapes(){
return shapes;
}
}
abstract class GeometricShape{
private int x;
private int y;
public GeometricShape(int x,int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
abstract public double getArea();
abstract public String toString();
}
class Rectangle extends GeometricShape{
public Rectangle(int x, int y, int nextInt, int nextInt1) {
super();
}
public getWidth(){
super();
}
public getLength(){
super();
}
#Override
public double getArea() {
return 0;
}
#Override
public String toString() {
return "Rectangle: [x:" + getX() + ", y:" + getY() + ", width: + " + getWidth() + " height: " + getHeight() + "]";
}
// body
}
Related
I asked this question on Math.se a few days ago, and got the following answer in pseudocode:
Function RandomCircleInside(centerX, centerY, radius):
Let newRadius = radius * Random()
Let radians = 2.0 * 3.14159265358979323846 * Random()
Let deviation = (radius - newRadius) * Sqrt(Random())
Let newX = centerX + deviation * Cos(radians)
Let newY = centerY + deviation * Sin(radians)
Return (newX, newY, newRadius)
End Function
I changed the pseudocode to Java and added my own changes to fit my needs. The new code looks like this:
Circle createNewCircle(int centerX, int centerY, int radius, int newR, Color newColor) {
int newRadius = radius * Random();
double radians = 2.0 * 3.141592653589793 * Random();
double deviation = (radius - newRadius) * Math.sqrt(Random());
System.out.println(radius + " - " + newRadius + " * sqrt(0 or 1) = " + (radius-newRadius) + " * (0 or 1) = " + deviation);
double newX = centerX + deviation * Math.cos(radians);
System.out.println(centerX + " + " + deviation + " * cos(" + radians + ") = " + (centerX + deviation) + " * " + Math.cos(radians));
double newY = centerY + deviation * Math.sin(radians);
int newCirX = (int) newX;
int newCirY = (int) newY;
Circle newCir = new Circle(newCirX, newCirY, newR*2, newR*2, newR, newColor, true);
return newCir;
}
The code itself is supposed to create a new Circle inside of a preexisting one. I created a circle class that looks like this:
import java.awt.Color;
import java.awt.Graphics;
public class Circle {
public int X, Y, Width, Height, radius;
public Color color;
public boolean toFill;
public Circle(int x, int y, int width, int height, int radius, Color color, boolean fill) {
X = x;
Y = y;
Width = width;
Height = height;
this.radius = radius;
this.color = color;
toFill = fill;
}
public void render(Graphics g) {
g.setColor(color);
for(int i=-5; i<5; i++) {
if(toFill) {
g.fillOval(X+i, Y+i, Width-i, Height-i);
} else {
g.drawOval(X+i, Y+i, Width-i, Height-i);
}
}
}
public boolean contains(Circle pBound) {
int pBoundCenterX = pBound.X+pBound.radius;
int cirCenterX = X+radius;
int diffBetweenCentersX = Math.abs(pBoundCenterX-cirCenterX);
int pBoundCenterY = pBound.Y+pBound.radius;
int cirCenterY = Y+radius;
int diffBetweenCentersY = Math.abs(pBoundCenterY-cirCenterY);
if(diffBetweenCentersX<= (pBound.radius+radius) && diffBetweenCentersX>=Math.abs(pBound.radius-radius)) { // X
if(diffBetweenCentersY>=Math.abs(pBound.radius-radius)) { // Y
return true;
}
}
return false;
}
public int getX() {
return X;
}
public int getWidth() {
return Width;
}
public int getRadius() {
return radius;
}
public void setWidth(int width) {
Width = width;
}
public int getHeight() {
return Height;
}
public void setHeight(int height) {
Height = height;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
My way of creating the new circle is this:
if(secInGame==timesForCircle[X] && !hasChanged) { // circle 2
Circle cir1 = cir;
cir = createNewCircle(cir1.X+(cir1.Width/2), cir1.Y+(cir1.Height/2), cir1.getRadius(), 135, Color.cyan);
hasChanged = true;
circleOn++;
circ++;
}
Where cir1 is the preexisting Circle and cir is the new circle.
Is there anything I didn't code correctly? I've tried a few different variations, but they all give the same result.
Before I implemented the pseudocode, my circles looked like this:
but now it looks like this:
All of my code can be found on github at: link
I think there are several issues in your code.
1. First of all it is not clear why your Circle has radius, Width and Height. For a circle all 3 things should be the same. Also your render in case toFill is true looks strange. Here is a simplified version (note: I didn't compile it so there might be some bugs):
public class Circle {
public int X, Y, radius;
public Color color;
public boolean toFill;
public Circle(int x, int y, int radius, Color color, boolean fill) {
X = x;
Y = y;
this.radius = radius;
this.color = color;
toFill = fill;
}
public void render(Graphics g) {
g.setColor(color);
final int r2 = 2*radius;
if(toFill) {
g.fillOval(X, Y, r2, r2);
}
else {
for(int i=-5; i<5; i++) {
g.drawOval(X+i, Y+i, r2-i, r2-i);
}
}
}
public boolean contains(Circle pBound) {
int pBoundCenterX = pBound.X+pBound.radius;
int cirCenterX = X+radius;
int diffBetweenCentersX = Math.abs(pBoundCenterX-cirCenterX);
int pBoundCenterY = pBound.Y+pBound.radius;
int cirCenterY = Y+radius;
int diffBetweenCentersY = Math.abs(pBoundCenterY-cirCenterY);
if(diffBetweenCentersX<= (pBound.radius+radius) && diffBetweenCentersX>=Math.abs(pBound.radius-radius)) { // X
if(diffBetweenCentersY>=Math.abs(pBound.radius-radius)) { // Y
return true;
}
}
return false;
}
public int getX() {
return X;
}
public int getRadius() {
return radius;
}
public void setX(int x) {
X = x;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
I didn't check your code, but I'd consider as a good practice:
renaming x and y into leftX and topY to avoid confusion with centerX/centerY meaning. Or change meaning to more typical center one.
declaring all your fields as private (see encapsulation);
declaring all your fields as final and remove all the setXyz methods (see immutability)
2. I don't understand why your createNewCircle has newR parameter and at the same time you generate a random newRadius in the first line. One of these definitely should be removed. Given that the parameter is always a constant 135 I think it should be removed.
3. Now I believe the main bug in your translation is in the lines
int newCirX = (int) newX;
int newCirY = (int) newY;
It probably should be something like
int newCirX = (int) newX - newRadius;
int newCirY = (int) newY - newRadius;
It looks like you messed with center vs top-left. Actually I think the fact that you made such a bug is an argument that supports renaming x and y I suggested in item #1.
3 diffrent classes 1 for handling Circle isntances ,1 for Square instances and the 3rd for comparrisons between them(main) . In the main function i find the circle (between c1..c4) and square (between s1...s5) and print the biggest circumference and area of them respectively.[so circle-circle and square-square comparison]
!!!! NOTE : Only the ones with the biggers radius or sides have the biggest circumference or area , so i only use r and a for comparisons.i dont know if its possible to return this if i use the area/circumference method(no , cause then i will only handle numbers ?).Correct me please.
Now i want to print the characteristics(x,y,r/a) of the geometric shape (circle/square) with the biggest perimeter. How can i do this ? Where do i compare?New class?[square-circle comparison]
public class Circle {
public double x,y,r;
public double circumference() {
return 2*(3.14)*r;
}
public double area() {
return 3.14*r*r;
}
public Circle bigger(Circle c){
if(c.r>r) return c; else return this;
}
public Circle(double x, double y, double r) {
this.x=x;
this.y=y;
this.r=r;
}
}
public class Square {
public double x,y,a;
public double perimeter() {
return 4*a;
}
public double area() {
return a*a;
}
public Square bigger(Square s){
if(s.a>a) return s; else return this;
}
public Square(double x, double y, double a) {
this.x=x;
this.y=y;
this.a=a;
}
}
public class CircleAndSquareTest {
public static void main(String[] args) {
Circle c1 = new Circle(0.0,0.0,1.0);
Circle c2 = new Circle(1.0,0.0,2.0);
Circle c3 = new Circle(0.0,2.0,4.0);
Circle c4 = new Circle(1.0,3.0,1.0);
Circle cb = c1.bigger(c2).bigger(c3).bigger(c4);
System.out.println("The circle with the biggest circumference has:\n");
System.out.println("x-axis value: " + cb.x + " y-axis value: " + cb.y + " radius: " + cb.r+"\n");
Square s1 = new Square(0.0,0.0,1.0);
Square s2 = new Square(0.0,0.0,1.0);
Square s3 = new Square(0.0,0.0,5.0);
Square s4 = new Square(4.0,2.0,2.0);
Square s5 = new Square(0.0,0.0,1.0);
Square sb = s1.bigger(s2).bigger(s3).bigger(s4).bigger(s5);
System.out.println("The square with the biggest area has:\n");
System.out.println("x-axis value: " + sb.x + " y-axis value: " +
sb.y + " side: " + sb.a);
}
}
Here's how to do it using Comparators and the Collections class to find the max value. This is untested but it should do what you want. Note I'm using static inner classes here but they can be standard classes defined in their own file if needs be - this is just for the purpose of creating a quick answer.
public interface Shape {
double getPerimeter();
double getArea();
}
public static class PerimeterComparator implements Comparator<Shape> {
#Override
public int compare(Shape a, Shape b) {
return Double.compare(a.getPerimeter(), b.getPerimeter());
}
}
public static class AreaComparator implements Comparator<Shape> {
#Override
public int compare(Shape a, Shape b) {
return Double.compare(a.getArea(), b.getArea());
}
}
public static class Circle implements Shape {
private final double x, y, r;
#Override
public double getPerimeter() {
return 2 * (3.14) * r;
}
#Override
public double getArea() {
return 3.14 * r * r;
}
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getR() {
return r;
}
}
public static class Square implements Shape{
private final double x, y, a;
#Override
public double getPerimeter() {
return 4 * a;
}
#Override
public double getArea() {
return a * a;
}
public Square(double x, double y, double a) {
this.x = x;
this.y = y;
this.a = a;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getA() {
return a;
}
}
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
List<Circle> circles = new ArrayList<>();
circles.add(new Circle(0.0,0.0,1.0));
circles.add(new Circle(1.0,0.0,2.0));
circles.add(new Circle(0.0,2.0,4.0));
circles.add(new Circle(1.0,3.0,1.0));
Circle largestCircle = Collections.max(circles, new PerimeterComparator());
System.out.println("The circle with the biggest circumference has:\n");
System.out.println("x-axis value: " + largestCircle.getX() + " y-axis value: " + largestCircle.getY() + " radius: " + largestCircle.getPerimeter() +"\n");
List<Square> squares = new ArrayList<>();
squares.add(new Square(0.0,0.0,1.0));
squares.add(new Square(0.0,0.0,1.0));
squares.add(new Square(0.0,0.0,5.0));
squares.add(new Square(4.0,2.0,2.0));
squares.add(new Square(0.0,0.0,1.0));
Square largestSquare = Collections.max(squares, new PerimeterComparator());
System.out.println("The square with the biggest area has:\n");
System.out.println("x-axis value: " + largestSquare.getX() + " y-axis value: " + largestSquare.getY() + " side: " + largestSquare.getA());
shapes.addAll(circles);
shapes.addAll(squares);
Shape largestPerimeter = Collections.max(shapes, new PerimeterComparator());
Shape largestArea = Collections.max(shapes, new AreaComparator());
System.out.printf("\nThe shape with the biggest perimeter is a %s and has has: a perimeter of: %f\n", largestPerimeter.getClass().getSimpleName(), largestPerimeter.getPerimeter());
System.out.printf("The shape with the biggest area is a %s and has has: an area of: %f\n", largestArea.getClass().getSimpleName(), largestArea.getArea());
}
Start by declaring a base interface, maybe called Shape that defines a method getPerimeterLength() for example.
Have all your shape classes implement that interface, and the corresponding method(s).
Now, a Square is also a Shape, and so is a Circle. Then you could put all these objects into an array of Shape. You iterate that array, and identify that entry with the maximum perimeter length. Then you simply call toString() on that object. Because you also overwrite the toString() method in all your classes to print the (different!) details each class has internally.
Ok so for class I have been working on some oblong questions based off an oblong class. The question I am having an issue with is to create a method to increase the height and width of the oblong by a user defined amount.
This is my main:
import java.util.Scanner;
public class Oblong6
{
public static void main(String [] args)
{
Oblong ob1 = new Oblong();
Scanner keyboardIn = new Scanner(System.in);
Oblong ob = new Oblong();
double h, w, x;
System.out.print ("Enter the height of the oblong:");
h = keyboardIn.nextDouble();
System.out.print ("Enter the width of the oblong:");
w = keyboardIn.nextDouble();
System.out.print (" Enter the amount to increment by ");
x = keyboardIn.nextInt();
ob.setHeight(h);
ob.setWidth(w);
ob.setX(x);
System.out.println (ob.incHeight());
System.out.println (ob.incWidth());
System.out.println("Height " + h);
System.out.println("Width " + w);
}
}
And this is the method I have created in the oblong class to increase them:
public class Oblong
{
// instance variables
private double height;
private double width;
private double x;
// constructor
public Oblong()
{
height = 0.0;
width = 0.0;
x = 0.0;
}
// methods
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public double setX(double x)
{
return x;
}
public void setWidth(double w)
{
width = w;
}
public void setHeight(double h)
{
height = h;
}
public double calculateArea()
{
return width * height;
}
public double calculatePerimeter()
{
return width + height * 2;
}
public boolean isSquare()
{
if(height == width)
{
return true;
}
else
{
return false;
}
}
public double incHeight()
{
{
return height + x ;
}
}
public double incWidth()
{
{
return width + x ;
}
}
}// end of class
but it only ever prints out the original height and width.
Your code:
public double incHeight()
{
{
return height + x ;
}
}
That just adds two numbers and returns the result.
It doesn't do anything else. The same is true for your other methods.
Whereas the purpose of the method seems to be to alter the state of the underlying object. But as said; the current implementation does not alter that state.
Hope that is good enough to help you to resolve your problem on your own.
Side note: read about Java syntax. Your extra pair of braces ... doesn't do anything either.
Whit this:
public double incWidth()
{
{
return width + x ;
}
}
You are returning width + 1 but you are not modifying the private attribute. Just do this:
public double incWidth(){
this.width = this.width + 1;
return this.width;
}
Also in setters you don't need to return anything. To change an attribute inside a class do something like:
private double value;
private void setValue( double value ) {
this.value = value;
}
With this.value you are refering to the private value inside the class. Without this you are refering to the parameter value of the method setValue.
Further reading:
How do getters and setters work?
Your instance variable x has not been set, hence the height + x will return height + 0.0.
change this:
public double setX(double x)
{
return x;
}
To this:
public double setX(double x)
{
this.x = x;
}
This will return value to be displayed, but it should be set for later use, so you need this :
public void incHeight()
{
setHeight(height + x) ;
}
and then :
System.out.println("Height " + height); // height not h
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Well since you folks helped me a lot with my last project, I thought I might find some assistance with the current one :)
The project has us practicing recursion and objects (just started learning about the latter). So we first create a "BasicStar", later a "Snowflake", then comes the "SuperSnowflake" and finally the dreaded "KochCurve".
So I the "BasicStar" was quite easy, and now the idea of the "Snowflake" is to recursively draw "BasicStar"s with smaller radiuses. I have uploaded three images (basic star, which I did successfully, snowflake the way it should be, and my snowflake) so it's easy to understand what I mean. My recursive method draws something very different, and I have no idea what I'm doing wrong. Any help would be great.
Thanks!
(P.S. The Main and Painter classes were made by the university faculty so even if there are things to improve there it won't be relevant. The rest was written by myself)
Main:
package recursion;
import java.util.Scanner;
/*
* the class main get from the user the shape he wish to draw,
* and call the drew method of the desired shape .
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the number of the shape you wish to draw:\n" +
" 1-example\n" +
" 2-BasicStar\n" +
" 3-Snowflake\n" +
" 4-SuperSnowflake\n" +
" 5-KochCurve\n" +
" 6-KochSnowflake\n");
int shape = sc.nextInt();
// chooses which shape to draw based on the number received
switch(shape){
/*
* An example given to you so you can see how the painted works.
* This example opens a frame, and draws a red line.
*/
case 1:
drawExample();
break;
case 2:
drawBasicStar();
break;
case 3:
drawSnowflake();
break;
case 4:
drawSuperSnowflake();
break;
case 5:
drawKochCurve();
break;
case 6:
drawKochSnowflake();
break;
default: System.out.println("invalid shape");
}
sc.close();
}
// Draw the example line
public static void drawExample(){
Painter.draw("example");
}
// Draw a BasicStar
public static void drawBasicStar(){
Painter.draw("BasicStar");
}
// Draw a Snowflake
public static void drawSnowflake(){
Painter.draw("Snowflake");
}
// Draw a SuperSnowflake
public static void drawSuperSnowflake(){
Painter.draw("SuperSnowflake");
}
// Draw a KochCurve
public static void drawKochCurve(){
Painter.draw("KochCurve");
}
// Draw a KochSnowflake
public static void drawKochSnowflake(){
Painter.draw("KochSnowflake");
}
}
Painter:
package recursion;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
/*
* open a frame named aShape and drew the given shape
*/
public class Painter extends Component {
private static final long serialVersionUID = 1L;
private static int SIZE = 600;
private static Painter painter;
private static Graphics g;
private static String shape = null;
// Create a frame and display it
public static void draw(String aShape) {
shape = aShape;
JFrame frame = new JFrame(shape);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
painter = new Painter();
frame.add(painter, null);
frame.pack();
frame.setVisible(true);
}
// returns the Frame's width
public static int getFrameWidth () {
return painter.getSize().width;
}
// returns the Frame's height
public static int getFrameHeight () {
return painter.getSize().height;
}
// changes the color of the lines to be drawn
public static void setColor (String color) {
if (color.equals("red")){
g.setColor(Color.red);
}
else if (color.equals("blue")){
g.setColor(Color.blue);
}
else if (color.equals("green")){
g.setColor(Color.green);
}
}
public static void drawLine (Pixel p1, Pixel p2) {
drawLine((int)Math.round(p1.getX()),(int)Math.round(p1.getY()),(int)Math.round(p2.getX()),(int)Math.round(p2.getY()));
}
// Draw a line on the frame
public static void drawLine (int x1, int y1, int x2, int y2) {
g.drawLine(x1, getFrameHeight()-y1, x2, getFrameHeight()-y2);
}
// Set the default size of the window frame to SIZE*SIZE pixels
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
// paint the frame - draw the shape given (call the draw method in that shape object)
public void paint(Graphics g) {
Painter.g = g;
try{
Object myShape = (Class.forName("recursion." + shape)).newInstance();
Object [] objs = null;
Class [] classes = null;
(Class.forName("recursion." + shape)).getMethod("draw", classes).invoke(myShape, objs);
}
catch(Exception e)
{
System.out.println("Can't handle shape " + shape);
System.out.println(e.toString());
System.out.println(e.getCause());
}
}
}
Pixel:
package recursion;
public class Pixel {
private double x;
private double y;
public Pixel(){
x = 0;
y = 0;
}
public Pixel(double x, double y){
this.x = x;
this.y = y;
}
public Pixel(Pixel center){
this();
if(center != null){
this.x = center.x;
this.y = center.y;
}
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void translate(Pixel p){
this.x = this.x + p.x;
this.y = this.y + p.y;
}
public void rotateRelativeToAxesOrigin(double theta){
double tempX = this.x;
double tempY = this.y;
this.x = ((tempX)*(Math.cos(theta)) - ((tempY)*(Math.sin(theta))));
this.y = ((tempX)*(Math.sin(theta)) - ((tempY)*(Math.cos(theta))));
}
public void rotateRelativeToPixel(Pixel p1, double theta){
double tempX = this.x;
double tempY = this.y;
Pixel translatedPixel = new Pixel(tempX-p1.getX(), tempY-p1.getY());
translatedPixel.rotateRelativeToAxesOrigin(theta);
this.x = translatedPixel.getX() + p1.getX();
this.y = translatedPixel.getY() + p1.getY();
}
}
BasicStar:
package recursion;
public class BasicStar {
private Pixel center;
private double radius;
public BasicStar(){
double height = Painter.getFrameHeight()/2;
double width = Painter.getFrameWidth()/2;
this.center = new Pixel (width, height);
double maxRadius = Math.min(width, height)/2;
this.radius = maxRadius/4;
}
public BasicStar(Pixel center, double radius){
this.center = new Pixel(center);
this.radius = radius;
}
public Pixel getCenter(){
return new Pixel(center);
}
public double getRadius(){
return this.radius;
}
public void draw(){
Pixel begin = new Pixel(this.center);
Pixel end = new Pixel(center.getX() + getRadius(), center.getY());
Painter.drawLine(begin, end);
end.rotateRelativeToPixel(center, (2*Math.PI)/6);
Painter.drawLine(begin, end);
end = new Pixel(center.getX() + getRadius(), center.getY());
end.rotateRelativeToPixel(center, (4*Math.PI)/6);
Painter.drawLine(begin, end);
end = new Pixel(center.getX() + getRadius(), center.getY());
end.rotateRelativeToPixel(center, (6*Math.PI)/6);
Painter.drawLine(begin, end);
end = new Pixel(center.getX() + getRadius(), center.getY());
end.rotateRelativeToPixel(center, (8*Math.PI)/6);
Painter.drawLine(begin, end);
end = new Pixel(center.getX() + getRadius(), center.getY());
end.rotateRelativeToPixel(center, (10*Math.PI)/6);
Painter.drawLine(begin, end);
}
}
Snowflake:
package recursion;
public class Snowflake {
private BasicStar basic;
private int depth;
public Snowflake(){
double height = Painter.getFrameHeight()/2;
double width = Painter.getFrameWidth()/2;
Pixel center = new Pixel (width, height);
double maxRadius = Math.min(width, height)/2;
double radius = maxRadius/4;
this.basic = new BasicStar(center, radius);
this.depth = 2;
}
public Snowflake(BasicStar basic, int depth){
this();
if(basic!=null){
this.basic = basic;
this.depth = depth;
}
}
public int getDepth(){
return this.depth;
}
public BasicStar getBasic(){
return this.basic;
}
public double getRadius(BasicStar basic){
return this.basic.getRadius();
}
public Pixel getBasicCenter(BasicStar basic){
return this.basic.getCenter();
}
public void draw(){
draw(this.depth, basic.getCenter(), basic.getRadius());
}
private void draw(int depth, Pixel center, double radius){
BasicStar basic = new BasicStar(center, radius);
if(depth==1){
basic.draw();
}
else{
Pixel p = new Pixel(center.getX() + radius, center.getY());
draw(depth - 1, p, (radius/3));
for(int i=0; i<6; i=i+1){
p.rotateRelativeToPixel(center, (2*Math.PI)/6);
BasicStar temp = new BasicStar(p, radius/3);
temp.draw();
}
}
}
}
This looks overly complicated to me. To be honest, I did not read all your code, but you can create a simple recursive function for drawing a snowflake just like this:
public void drawSnowflake(Graphics g, int x, int y, int size, int level) {
for (int a = 0; a < 360; a += 60) {
double rad = a * Math.PI / 180;
int x2 = (int) (x + Math.cos(rad) * size);
int y2 = (int) (y + Math.sin(rad) * size);
g.drawLine(x, y, x2, y2);
if (level > 0) {
drawSnowflake(g, x2, y2, size/3, level-1);
}
}
}
What this code does is: It draws the lines of a star using basic trigonometry (don't forget to convert angles to radians!), and then calls itself with a smaller size and level for the positions at the ends of the spikes. Embedding this into an actual GUI is left as an excercise to the reader.
I'm working on a lab for school and I have it almost completed, but there's one part that I can't get to work. The inheritance works except when I get to Cube. For some reason, it won't calculate the Area or Volume (it just comes up with 0). I'm thinking it's a problem with the way I have the inheritance from Square to Cube. Help would be awesome!
package InheritanceTest;
import javax.swing.JOptionPane;
public class InheritanceTest {
public static void main(String[] args) {
String input = "";
Point point = new Point();
input = getinput("Set variable X");
point.setx(input);
input = getinput("Set variable Y");
point.sety(input);
System.out.println("Point, x = " + point.getx() + " y = " + point.gety());
Square square = new Square();
input = getinput("Set variable Side Length");
square.setSideLength(input);
System.out.println("Square, x = " + point.getx() + " y = " + point.gety()
+ " Area = " + square.getAreaOfSquare() + " Perimeter = "
+ square.getPerimeterOfSquare());
Cube cube = new Cube();
input = getinput("Set variable depth");
cube.setDepth(input);
System.out.println("cube, x = " + point.getx() + " y = " + point.gety()
+ " Depth = " + cube.getDepth() + " Area = " + cube.getAreaOfCube()
+ " Volume = " + cube.getVolumeOfCube());
}
private static String getinput(String string) {
String x = JOptionPane.showInputDialog(string);
return x;
}
}
package InheritanceTest;
public class Cube extends Square {
private int depth;
Cube() {
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d) {
super(x, y, sideLength);
this.depth = d;
}
public int getAreaOfCube() {
return (6 * sideLength * sideLength);
}
public int getVolumeOfCube() {
return (sideLength * sideLength * sideLength);
}
public String getDepth() {
return Integer.toString(depth);
}
public void setDepth(String i) {
depth = Integer.parseInt(i);
}
}
package InheritanceTest;
public class Point {
private int x;
private int y;
Point() {
x = 0;
y = 0;
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
public String getx() {
return Integer.toString(x);
}
public String gety() {
return Integer.toString(y);
}
public void setx(String input) {
x = Integer.parseInt(input);
}
public void sety(String input) {
y = Integer.parseInt(input);
}
}
package InheritanceTest;
public class Square extends Point {
protected int sideLength;
Square() {
super();
sideLength = 0;
}
Square(int x, int y, int l) {
super(x, y);
this.sideLength = l;
}
public int getAreaOfSquare() {
return sideLength * sideLength;
}
public int getPerimeterOfSquare() {
return sideLength + sideLength;
}
public String getSideLength() {
return Integer.toString(sideLength);
}
public void setSideLength(String input) {
sideLength = Integer.parseInt(input);
}
}
When you create cube (new Cube()) you aren't setting the side length (or x and y) for the Square Object it extends.
Cube(){
// This is the constructor called.
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d){
super(x, y, sideLength);
this.depth = d;
}
You probably want extract the x,y and length values into variables and use "new Cube(x, y, length, depth)"
Something like the following
String x = getinput("Set variable X");
String y = getinput("Set variable Y");
String sideLength = getinput("Set variable Side Length");
String depth getinput("Set variable depth");
Cube cube = new Cube(x, y, sideLength, depth);
Look at how you are defining getVolumeOfCube(). You are calculating volume with sideLength, but you never set sideLength to any non-zero value. Change sideLength to depth and you will get the value you are looking for.