How To Use Methods With Array In Java? - java

My first question here so please point out my mistakes. And to be honest I couldn't find any similar questions.
So I am trying to write something very basic and I really can't figure why I can't call a method from my Util Class in my Main class.
Util class
private double accumulatedArea;
private double accumulatedCircumference;
public static double getAccumulatedArea(Shape[] shapes) {
double accumulatedArea = 0;
for (Shape s : shapes) {
accumulatedArea = accumulatedArea + s.area();
return accumulatedArea;
}
return accumulatedArea;
}
public static double getAccumulatedCircumference(Shape[] shapes) {
double accumulatedCircumference = 0;
for (Shape q : shapes) {
accumulatedCircumference = accumulatedCircumference + q.circumference();
return accumulatedCircumference;
}
return accumulatedCircumference;
}
public String toString() {
return "Number: ";
}
}
and Main class
public static void main(String[] args) {
Shape[] shapes = new Shape[4];
shapes[0] = new Circle(100);
shapes[1] = new Circle(23);
shapes[2] = new Rectangle(10, 20);
shapes[3] = new Rectangle(8, 12);
System.out.println("Area of the circle 1: " + shapes[0].area() + " and its circumference is: " + shapes[0].circumference());
System.out.println("Area of the circle 2: " + shapes[1].area() + " and its circumference is: " + shapes[1].circumference());
System.out.println("Area of the rectangle 1: " + shapes[2].area() + " and its circumference is: " + shapes[2].circumference());
System.out.println("Area of the rectangle 2: " + shapes[3].area() + " and its circumference is: " + shapes[3].circumference());
//Small test
System.out.println("Number of shapes are in the system: " + shapes.length);
//????? What to do here??
for (int p = 0; p < shapes.length; p++) {
Shape[p].getAccumulatedArea();
}
}
}
How can I call my getAccumulatedArea and getAccumulatedCircumference methods??
Been searching for couple of days now and I really don't have any idea how.
Just in case there is also 2 Rectangle and Circle classes that I use. They are very similar so I am only putting one.
private double radius;
private double circumference;
private double area;
private ArrayList<Circle> circles;
//throws Exception gives error! learn how to do exceptions!
public Circle(double radius) {
super();
if(radius > 0) {
this.radius = radius;
}
else {
System.out.println("Throw new Exception!!");
}
}
public void setRadius(double radius) throws Exception {
if (radius < 0) {
throw new Exception();
}
else {
this.radius = radius;
}
}
public void setCircumference(double circumference) throws Exception {
if (circumference < 0) {
throw new Exception();
}
else {
this.circumference = circumference;
}
}
public void setArea(double area) {
if (area <= 0) {
System.out.println("Please check your input!");
}
else {
this.area = area;
}
}
public double getRadius() {
return radius;
}
public double getCircumference() throws Exception{
if (radius < 0) {
throw new Exception();
}
else {
return circumference;
}
}
public double getArea() throws Exception{
if (radius < 0) {
throw new Exception();
}
else {
return area;
}
}
#Override
public double circumference() {
return 2 * Math.PI * radius;
}
#Override
public double area() {
return radius * radius * Math.PI;
}
}
The code seems kinda messy but that's because I've been trying everything :) Any advice is welcome. Btw I was using Arraylist but according to some people I know, using Array is much better in this circumstance.

The methods in your Util class are static. A static method should be invoked on the class it is declared as part of. Both of your methods you have declared to take a parameter of type Shape[]. So you should invoke them like so:
Util.getAccumulatedArea(shapes)
…where shapes is a value of type Shape[].

Related

resizing javafx shapes positions without scaling them

i wan't to create effect similar to that of photoshop when you press ctrl+T that produces frame around the object and resize but i want to just change the position of the contained object not scaling them what i created so far does the job but the movement is exagerrated and i can't figure out what is wrong with my codehere i am just trying with the northwest handler
thanks in advance
here is images illustrating exactly what i want
the first image is original group with blue circles are controllers
the second is the group after resizing the group by dragging the north west
but the components gets scaled also
the third one is exactly what i want to achieve only change positions without changing the scale
//this creates the bounding box
public static void cr_resizer(Group root,double x,double y,double X,double Y) {
Rectangle major=new Rectangle(x-10,y-10,X-x+20,Y-y+20);
major.setFill(Color.TRANSPARENT);
major.setId("major");
major.setStrokeWidth(3);
major.setStroke(Color.BLUE);
major.setDisable(true);
Circle NW=new Circle(x-10,y-10,3);
Circle N=new Circle(((x+X)/2),y-10,3);
Circle NE=new Circle(X+10,y-10,3);
Circle W=new Circle(x-10,(Y+y)/2,3);
Circle E=new Circle(X+10,(Y+y)/2,3);
Circle SE=new Circle(X+10,Y+10,3);
Circle S=new Circle(((x+X)/2),Y+10,3);
Circle SW=new Circle(x-10,Y+10,3);
resize_move( root,NW,SE);
root.getChildren().addAll(major,NW,N,NE,SE,S,SW,E,W);
}
//this function calculates the calculate the distance of the mover point from the opposing point
// to caclulate the scaling factor theen apply it to componnents of the group
public static void resize_move(Group root,Circle mover,Circle op) {
double[]start={mover.getCenterX(),mover.getCenterY()};
double[]end={op.getCenterX(),op.getCenterY()};
double[]strt_length=dis2_vec_d(start, end);
mover.setOnMouseClicked(ev->{
difx=ev.getX();
dify=ev.getY();
});
mover.setOnMouseDragged(ev->{
double diffx=ev.getX()-difx;
double diffy=ev.getY()-dify;
System.out.println(diffx);
System.out.println(diffy);
difx=ev.getX();
dify=ev.getY();
mover.setCenterX(ev.getX());
mover.setCenterY(ev.getY());
double[] newp= {mover.getCenterX(),mover.getCenterY()};
double[]end_length=dis2_vec_d(newp, end);
double[]factor = {end_length[0]/strt_length[0],end_length[1]/strt_length[1]};
for (Node nod:root.getChildren()) {
if (nod instanceof Circle) {
if (nod != mover) {
move_circ((Circle) nod,op,factor);
}
}
}
});
}
//this function relocate the position of the circle according to the position of the custom axis point
public static void move_circ(Circle cir,Circle op,double[]factor) {
double[] axis= {op.getCenterX(),op.getCenterY()};
double[] strt_point= {cir.getCenterX(),cir.getCenterY()};
double[] nstrt_point= new_cord(axis,strt_point,factor);
cir.setCenterX(nstrt_point[0]);
cir.setCenterY(nstrt_point[1]);
}
//this function scale the position of the point in relation to another point
public static double[] new_cord(double[]axis,double[]point,double[]factor) {
double[]strt_length=dis2_vec_d(point,axis);
double[]new_length= {strt_length[0]*factor[0],strt_length[1]*factor[1]};
double[]new_point= {new_length[0]+axis[0],new_length[1]+axis[1]};
return new_point;
}
//this function calculates the distance
public static double[] dis2_vec_d(double[]p1,double[]p2) {
double[] vec = new double[2];
vec[0]=p1[0]-p2[0];
vec[1]=p1[1]-p2[1];
return vec;
}
It looks like you just want to make your Node draggable. I created a class that does this, pasted below.
You might have to replace a few instances of a class called GameScreen in my code below.
public class Draggable {
////////////////////////////////////////////////////////////////////////////
//variables
AtomicBoolean myPressed = new AtomicBoolean(false);
Point2D myInitialTranslates;
Point2D dragInitialTranslates;
EventHandler<? super MouseEvent> onMouseReleased;
EventHandler<? super MouseEvent> onMousePressed;
EventHandler<? super MouseEvent> onMouseDragged;
OnDrag onDrag;
boolean stayWithinBounds = true;
double minX = 0;
double maxX = WIDTH;
double minY = 0;
double maxY = GameScreen.PLAY_AREA_HEIGHT;
boolean doNotTranslate = false;
//handleX and handleY are offsets used strictly for the callbacks, they are not used for the translation of the destination Node.
double handleX = 0;
double handleY = 0;
double X;
double Y;
boolean reverseX = false;
boolean reverseY = false;
float amountOfTargetNodeToAllowOutsideLimit = 0f;
public void setOnDrag(OnDrag onDrag) {
this.onDrag = onDrag;
}
////////////////////////////////////////////////////////////////////////////
//constructors
public Draggable() {
}
public Draggable(double handleX, double handleY) {
this.handleX = handleX;
this.handleY = handleY;
}
////////////////////////////////////////////////////////////////////////////
//methods
public void makeDraggable(Node source, Node target, double dragAdjustmentRatioX, double dragAdjustmentRatioY) {
source.setOnMouseDragged((MouseEvent event) -> {
if (myPressed.get() && !doNotTranslate) {
double x = myInitialTranslates.getX() - dragInitialTranslates.getX() + dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
double y = myInitialTranslates.getY() - dragInitialTranslates.getY() + dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
double localMaxX = maxX - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
double localMinX = minX - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
if (x > localMinX && x < localMaxX) {
target.setTranslateX(x);
} else {
// Log.debug("X is not within range. x = " + x);
}
double localMaxY = maxY - target.getBoundsInLocal().getHeight() * amountOfTargetNodeToAllowOutsideLimit;
double localMinY = minY - target.getBoundsInLocal().getWidth() * amountOfTargetNodeToAllowOutsideLimit;
if (y > localMinY && y < localMaxY) {
target.setTranslateY(y);
} else {
// Log.debug("Y is not within range. x = " + y);
}
} else {
}
if (onMouseDragged != null) {
onMouseDragged.handle(event);
}
if (onDrag != null) {
if (reverseX) {
X = handleX + dragInitialTranslates.getX() - dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
} else {
X = handleX - dragInitialTranslates.getX() + dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX());
}
if (reverseY) {
Y = handleY + dragInitialTranslates.getY() - dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
} else {
Y = handleY - dragInitialTranslates.getY() + dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY());
}
onDrag.handle(X, Y);
}
});
source.setOnMousePressed((MouseEvent event) -> {
myInitialTranslates = new Point2D(target.getTranslateX(), target.getTranslateY());
dragInitialTranslates = new Point2D(
dragAdjustmentRatioX * GameScreen.instance.scaleXToScreen(event.getSceneX()),
dragAdjustmentRatioY * GameScreen.instance.scaleYToScreen(event.getSceneY()));
myPressed.set(true);
if (onMousePressed != null) {
onMousePressed.handle(event);
}
GameScreen.setCursorMove();
});
source.setOnMouseReleased((MouseEvent event) -> {
myPressed.set(false);
handleX = X;
handleY = Y;
if (onMouseReleased != null) {
onMouseReleased.handle(event);
}
GameScreen.setCursorCustom();
});
}
public void makeDraggable(Node node, double dragAdjustmentRatioX, double dragAdjustmentRatioY) {
makeDraggable(node, node, dragAdjustmentRatioX, dragAdjustmentRatioY);
}
public void setOnMouseReleased(EventHandler<? super MouseEvent> onMouseReleased) {
this.onMouseReleased = onMouseReleased;
}
public void setOnMousePressed(EventHandler<? super MouseEvent> onMousePressed) {
this.onMousePressed = onMousePressed;
}
public void setOnMouseDragged(EventHandler<? super MouseEvent> onMouseDragged) {
this.onMouseDragged = onMouseDragged;
}
public void setAmountOfTargetNodeToAllowOutsideLimit(float amountOfTargetNodeToAllowOutsideLimit) {
this.amountOfTargetNodeToAllowOutsideLimit = amountOfTargetNodeToAllowOutsideLimit;
}
public interface OnDrag {
public void handle(double x, double y);
}
public boolean isStayWithinBounds() {
return stayWithinBounds;
}
public void setStayWithinBounds(boolean stayWithinBounds) {
this.stayWithinBounds = stayWithinBounds;
}
public void setMinMax(double minX, double maxX, double minY, double maxY) {
this.maxX = maxX;
this.minX = minX;
this.minY = minY;
this.maxY = maxY;
}
public void setDoNotTranslate(boolean doNotTranslate) {
this.doNotTranslate = doNotTranslate;
}
public boolean isReverseX() {
return reverseX;
}
public void setReverseX(boolean reverseX) {
this.reverseX = reverseX;
}
public boolean isReverseY() {
return reverseY;
}
public void setReverseY(boolean reverseY) {
this.reverseY = reverseY;
}
public double getHandleX() {
return handleX;
}
public void setHandleX(double handleX) {
this.handleX = handleX;
}
public double getHandleY() {
return handleY;
}
public void setHandleY(double handleY) {
this.handleY = handleY;
}
}
GameScreen.instance.scaleXToScreen and GameScreen.instance.scaleYToScreen just set this to 1. In the future if you scale your window, you might need to adjust for it.
GameScreen.WIDTH and GameScreen.PLAY_HEIGHT set tot he width and height of your scene.
The two method calls to change the mouse cursor can be deleted.
The way you use it is like this...
new Draggable().makeDraggable(nodeYouWantToDrag, 1, 1);
and thats that.
EDIT: it also has callbacks for basic events like onDrag, onMousePressed, onMouseDragged, and onMouseReleased.

Cannot Making Radius Exception for Circle Own Exception

the exception cannot appear, I apparently don't know where is the problem. I want to make own exception for circle radius. For example, if my input is negative value, then the exception need to appear. I made 3 classes. TestCircle.java, Circle.java and IllegalRadiusException.java
TestCircle.java
package circle;
public class TestCircle {
public static void main(String[] args) {
double newRad;
try {
Circle A = new Circle();
A.InputRadius();
A.Calculation();
newRad = A.getRadius();
A.Result();
} catch (IllegalRadiusException e) {
System.out.println(e);
}
}
}
Circle.java
package circle;
import java.util.Scanner;
public class Circle {
Scanner input = new Scanner(System.in);
private double radius;
private double area;
//this is consturctor method
public Circle() throws IllegalRadiusException {
if (radius >= 0) {
this.radius = radius;
this.area = area;
} else {
throw new IllegalRadiusException("Radius Cannot be Negative");
}
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setArea(double area) {
this.area = area;
}
public double getArea() {
return area;
}
//------------------------------------------------------------//
public void Calculation() {
area = 3.142 * radius * radius;
}
public void InputRadius() {
System.out.print("Radius: ");
radius = input.nextDouble();
}
public void Result() {
System.out.println("");
System.out.println("Radius: " + radius);
System.out.println("Area: " + area);
}
}
IllegalRadiusException.java
package circle;
public class IllegalRadiusException extends Exception {
//Extra kena tambah 'extends Exception'
//WAJIB KENA LETAK untuk CREATE OWN EXCEPTION
public IllegalRadiusException() {
super();
}
public IllegalRadiusException(String message) {
super(message);
}
}
In your code, the constructor would be called only once, at the time of object's instantiation.
You've added the check for exception, only in this constructor.
For your example to work as needed, you need to throw exceptions from your InpurRadius method too, if the user enters an invalid value.
Change your method to this.
public void InputRadius() throws IllegalRadiusException {
System.out.print("Radius: ");
double entered_radius = input.nextDouble();
if (entered_radius >= 0) {
this.radius = entered_radius;
this.area = area;
} else {
throw new IllegalRadiusException("Radius Cannot be Negative");
}
}
You do not pass value to radius in constructor so it is not initialized (0). So the if statement will always pass since 0 == 0 :). Pass
public Circle(double radius) // something like this
and assign it inside constructor to radius

How would I remove a shape from this array using the shape's area?

I have this program that's supposed to add a shape to an array, using its type (rectangle, triangle, circle) and its dimensions (length/width, base/height, radius). It's also supposed to be able to remove a shape from the array. Currently, I can add a shape to the array, but when I try to remove it (which is based on shape type and area, rather than shape type and dimensions), it will print out that it cannot find the shape.
Example: I add a Rectangle with a length of 3 and width of 2. Its area is 6. When I try to remove a Rectangle with an area of 6, it does not remove this rectangle from the array because it supposedly cannot find it.
For clarification, the main issue comes in the removeAShapeDialogue part in the Front-End and the removeShape method in the Collection part of the code.
Notes:
Shape is an interface
I cannot create any other classes, methods, or interfaces as per instruction, so there must be a solution using whatever is here.
I don't think the problem is in the Rectangle, Triangle, or Circle classes
I'm also having problems with the selection sort in the ShapeCollection class, so any help there would be greatly appreciated.
Front-End
import java.util.Scanner;
public class ShapeFrontEnd {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Shapes Collection.");
ShapeCollection shapes = new ShapeCollection();//New instance of ShapeCollection
boolean quit = false;
while(!quit)//Runs until quits
{
printOptions();
int pick = keyboard.nextInt();
keyboard.nextLine();
switch(pick)
{
case 1://Add shape
shapes.addShape(makeAShapeDialogue());
break;
case 2://Remove shape
shapes.removeShape(removeAShapeDialogue());
break;
case 9://Quit
quit = true;
System.out.println("Goodbye");
System.exit(0);
break;
default:
System.out.println("Invalid input.");
}
System.out.println("Current Shapes:");
shapes.printShapes(shapes);
}
}
//Helper Methods
public static void printOptions()//Prints user's input options
{
System.out.println("Enter 1: Add a shape\nEnter 2: Remove a shape\nEnter 9: Quit");
}
public static Shape makeAShapeDialogue()//Prints the dialogue after user enters "1"
{
Scanner keyboard = new Scanner(System.in);
Shape newShape;
System.out.println("What type of shape? Rectangle, Triangle, or Circle?");
String shapeType = keyboard.nextLine();
if(shapeType.equalsIgnoreCase("rectangle"))
{
System.out.println("Enter length.");
double length = keyboard.nextDouble();
System.out.println("Enter height.");
double height = keyboard.nextDouble();
keyboard.nextLine();
newShape = new Rectangle(length, height);
}
else if(shapeType.equalsIgnoreCase("triangle"))
{
System.out.println("Enter base.");
double base = keyboard.nextDouble();
System.out.println("Enter height.");
double height = keyboard.nextDouble();
keyboard.nextLine();
newShape = new Triangle(base, height);
}
else if(shapeType.equalsIgnoreCase("circle"))
{
System.out.println("Enter radius.");
double radius = keyboard.nextDouble();
keyboard.nextLine();
newShape = new Circle(radius);
}
else
{
newShape = null;
}
return newShape;
}
public static Shape removeAShapeDialogue()
{
ShapeCollection shapes = new ShapeCollection();
Scanner keyboard = new Scanner(System.in);
Shape newShape;
System.out.println("What type of shape? Rectangle, Triangle, or Circle?");
String shapeType = keyboard.nextLine();
System.out.println("Enter area.");
double area = keyboard.nextDouble();
keyboard.nextLine();
if(shapeType.equalsIgnoreCase("rectangle"))
{
newShape = new Rectangle();
}
if(shapeType.equalsIgnoreCase("triangle"))
{
newShape = new Triangle();
}
if(shapeType.equalsIgnoreCase("circle"))
{
newShape = new Circle();
}
else
{
newShape = null;
}
return newShape;
}
}
Collection/Array Class
public class ShapeCollection {
private Shape[] shapes;
public static final int MAX_SHAPES = 5;
//Constructor
public ShapeCollection()
{
shapes = new Shape[MAX_SHAPES];
}
//Method to get all the Shapes
public Shape[] getShapes()
{
return this.shapes;
}
//Add Shape
public void addShape(Shape aShape)
{
for(int i=0;i<shapes.length;i++)
{
if(shapes[i] == null)
{
shapes[i] = aShape;
return;
}
}
System.out.println("You cannot fit any more shapes.");
}
//Remove Shape
public void removeShape(Shape aShape)
//public void removeShape(String aShapeType, double anArea)
{
for(int i=0;i<shapes.length;i++)
{
System.out.println(shapes[i]);
if(shapes[i] != null && shapes[i].equals(aShape))
//if(shapes[i] != null && shapes[i].getType().equals(aShapeType) && shapes[i].getArea() == (anArea))
{
shapes[i] = null;
return;
}
}
System.out.println("Cannot find that shape.");
}
//Sort Shapes
private void sortShapes()
{
for(int i=0;i<shapes.length-1;i++)
{
int smallestIndex = i;
for(int j=i+1; j<shapes.length;j++)
{
if(shapes[j].getArea() < shapes[smallestIndex].getArea())
{
smallestIndex = j;
}
/*if(smallestIndex !=i)
{
Shape number = shapes[i];
shapes[i] = shapes[smallestIndex];
shapes[smallestIndex] = number;
}*/
}
Shape temp = shapes[smallestIndex];
shapes[smallestIndex] = shapes[i];
shapes[i] = temp;
}
}
//Prints Shapes
public void printShapes(ShapeCollection shapeC)
{
//sortShapes();
for(Shape s : shapeC.getShapes())
{
if(s == null)
continue;
System.out.println(s);
System.out.println();
}
}
}
Shape Interface
public interface Shape {
public double getArea();
public String toString();
public String getType();
}
Rectangle Class
public class Rectangle implements Shape{
//Attributes
private double length;
private double width;
//Constructors
public Rectangle()//Default
{
this.length = 0.0;
this.width = 0.0;
}
public Rectangle(double aLength, double aWidth)//Parameterized
{
this.setLength(aLength);
this.setWidth(aWidth);
}
//Accessors
public double getLength()
{
return this.length;
}
public double getWidth()
{
return this.width;
}
//Mutators
public void setLength(double aLength)
{
if(aLength>0)
{
this.length = aLength;
}
else
{
System.out.println("Invalid length.");
}
}
public void setWidth(double aWidth)
{
if(aWidth>0)
{
this.width = aWidth;
}
else
{
System.out.println("Invalid width.");
}
}
//Other Methods
public double getArea()
{
return this.length*this.width;
}
public String getType()
{
return "RECTANGLE";
}
public String toString()
{
return getType() + " | Length: " + this.length + " | Width: " + this.width + " | Area: " + getArea();
}
}
Triangle Class
public class Triangle implements Shape{
//Attributes
private double base;
private double height;
//Constructors
public Triangle()
{
this.base = 0.0;
this.height = 0.0;
}
public Triangle(double aBase, double aHeight)
{
this.setBase(aBase);
this.setHeight(aHeight);
}
//Accessors
public double getBase()
{
return this.base;
}
public double getHeight()
{
return this.height;
}
//Mutators
public void setBase(double aBase)
{
if(aBase>0)
{
this.base = aBase;
}
else
{
System.out.println("Invalid base.");
}
}
public void setHeight(double aHeight)
{
if(aHeight>0)
{
this.height = aHeight;
}
else
{
System.out.println("Invalid height.");
}
}
//Other Methods
public double getArea()
{
return (this.base*this.height)/2;
}
public String getType()
{
return "TRIANGLE";
}
public String toString()
{
return getType() + " | Base: " + this.base + " | Height: " + this.height + " | Area: " + getArea();
}
}
Circle Class
public class Circle implements Shape{
//Attributes
private double radius;
//Constructors
public Circle()
{
this.radius = 0.0;
}
public Circle(double aRadius)
{
this.setRadius(aRadius);
}
//Accessors
public double getRadius()
{
return this.radius;
}
//Mutators
public void setRadius(double aRadius)
{
if(aRadius>0)
{
this.radius = aRadius;
}
else
{
System.out.println("Invalid radius.");
}
}
//Other Methods
public double getArea()
{
return Math.PI*(radius*radius);
}
public String getType()
{
return "CIRCLE";
}
public String toString()
{
return getType() + " | Radius: " + this.radius + " | Area: " + getArea();
}
}
You're comparing shapes using their equals method: shapes[i].equals(aShape) but you haven't implemented it, so you're really comparing using the default Object.equals() method, which doesn't know what Shape is, and instead compares the Object's references.

JAVA - Answers are not calculating upon output?

Doing a what I thought would be a very very easy output lab for AP, I thought I was doing everything correctly, but the output keeps coming out as "The area is :: " + 0.0" when the "0.0" is supposed to be the calculated area of the circle. Here are the two classes:
Circle Class:
public class Circle
{
private double radius;
private double area;
public void setRadius(double rad)
{
rad = radius;
}
public void calculateArea( )
{
area = (3.14159*(radius*radius));
}
public void print( )
{
System.out.println("The area is :: " + area);
}
}
Circle Runner Class:
public class CircleRunner
{
public static void main( String[] args )
{
Circle test = new Circle ( );
test.setRadius(7.5);
test.calculateArea( );
test.print( );
test.setRadius(10);
test.calculateArea( );
test.print( );
test.setRadius(72.534);
test.calculateArea( );
test.print( );
test.setRadius(55);
test.calculateArea( );
test.print( );
}
}
Thanks!
Your setter is wrong, so your radius stays 0, it should be
public void setRadius(double rad) {
radius = rad;
}
You are assigning the variables in reverse order. It should be:
radius = rad;
And not:
rad = radius;
You need to use this to reference your radius in your setRadius Method. or swap the two values. You should assign " rad " to " radius" and not vis versa, since you will be recieving rad from the method.
public class Circle {
private double radius;
private double area;
public Circle() {
}
public void setRadius(double rad) {
this.radius = rad;
}
public void calculateArea() {
area = (3.14159*(radius*radius));
}
public void print() {
System.out.println("The area is :: " + area);
}
}

java.lang.IncompatibleClassChangeError: Implementing Utility class

Im trying to implement a simple rectangle, but i am getting incompatible class change error..
Expecting non-static method Utility.printLine()
The error is on line,
util.printLine();
Any help??
the complete code is as follow..
import java.lang.*;
import java.util.*;
class Rectangle
{
private double height;
private double width;
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
public void setHeight(double x)
{
if(x<=0)
{
System.out.println("Invalid Height");
System.exit(0);
}
else
{
height = x;
}
}
public void setWidth(double x)
{
if(x<=0)
{
System.out.println("Invalid Width");
System.exit(0);
}
else
{
width = x;
}
}
public double getArea()
{
double a;
a = height*width;
return a;
}
public double getPerimeter()
{
double p;
p = 2*(height+width);
return p;
}
}
class Utility
{
public void printLine()
{
for(int i=1;i<=40;i++)
{
System.out.print("=");
}
System.out.println();
}
public void printLine(char ch)
{
for(int i=1;i<=40;i++)
{
System.out.print(ch);
}
System.out.println();
}
public void printLine(char ch, int x)
{
for(int i=1;i<=x;i++)
{
System.out.print(ch);
}
System.out.println();
}
}
class RectTest7
{
public static void main(String args[])
{
double area, peri, x;
Rectangle r = new Rectangle();
Scanner input = new Scanner(System.in);
Utility util = new Utility();
System.out.print("Enter height : ");
x = input.nextDouble();
r.setHeight(x);
System.out.print("Enter width : ");
x = input.nextDouble();
r.setWidth(x);
area = r.getArea();
peri = r.getPerimeter();
util.printLine();
System.out.println("Height : "+r.getHeight());
util.printLine();
System.out.println("Width : "+r.getWidth());
util.printLine();
System.out.println("Area : "+area);
util.printLine();
System.out.println("Perimeter : "+peri);
util.printLine();
r = null;
}
}

Categories

Resources