Cannot find symbol in method changeRecL but declared in main method - java

I am a new programmer and i am getting the error cannot find symbol in my ShapeApp class.
My error is
System.out.println("Current length of rectangle is: " + r1.getLength());
^
symbol: variable r1
location: class ShapeApp
Please try and explain it in a simpler way. Thank you very much and my codes are below.
public class Rectangle
{
protected double length;
protected double width;
public Rectangle() { }
public Rectangle(double l,double w)
{
length = l;
width = w;
}
public void setLength(double l) {length = l;}
public double getLength() {return length;}
public void setWidth(double w) {width = w;}
public double getWidth() {return width;}
public double findArea() {return length * width;}
public String toString()
{
return "\tLength " + length + "\tWidth " + width;
}
}
public class Box extends Rectangle
{
private double height;
public Box() { }
public Box(double l,double w,double h)
{
super(l,w);
height = h;
}
public void setHeight(double h) {height = h;}
public double getHeight() {return height;}
public double findArea() {return ((super.findArea() * 2) + (2 * height * width) + (2 * height * length));}
public double findVolume() {return super.findArea() * height;}
public String toString()
{
return super.toString() + "\tHeight " + height;
}
}
import java.util.*;
public class ShapeApp
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(20,10);
Box b1 = new Box(10,5,5);
int options;
Scanner input = new Scanner(System.in);
do{
displayMenu();
options = input.nextInt();
switch(options)
{
case 1: changeRecL();
break;
case 2: changeBoxL();
break;
case 3: changeBoxH();
break;
case 4: displayAreaRec();
break;
case 5: displaySaBox();
break;
case 6: displayVoBox();
break;
case 0: System.out.println("Exiting Program");
break;
default: System.out.println("Invalid Option. ");
}
}while(options != 0);
}
public static void displayMenu()
{
System.out.println("-------------------------------MENU-------------------------------");
System.out.println("[1] Change the length of rectangle");
System.out.println("[2] Change the length of box");
System.out.println("[3] Change the height of box");
System.out.println("[4] Display the area of rectangle");
System.out.println("[5] Display the surface area of box");
System.out.println("[6] Display the volume of box");
System.out.println("[0] Exit");
System.out.println("------------------------------------------------------------------");
System.out.println("Enter your option:");
}
public static void changeRecL()
{
Scanner input = new Scanner(System.in);
System.out.println("Current length of rectangle is: " + r1.getLength());
System.out.println("Enter new length of rectangle: ");
double nlength = input.nextDouble();
r1.setLength(nlength);
}
public static void changeBoxL()
{
}
public static void changeBoxH()
{
}
public static void displayAreaRec()
{
}
public static void displaySaBox()
{
}
public static void displayVoBox()
{
}
}

That's because you havent defined r1 in your method changeRecL.
Perhaps you wanted to pass that r1 from main to your method like below:
case 1: changeRecL(r1);
And accept R1 as below in the same:
public static void changeRecL(Rectangle r1)

When you define an object class you can make several instances of the class as objects. There's not only one Rectangle r1. If you want to use only one rectangle for everything you should implement a Singleton class.
public class Rectangle {
double len;
double wid;
private static Rectangle instance = null;
protected Rectangle() {
// Exists only to defeat instantiation.
}
public static Rectangle getInstance() {
if(instance == null) {
instance = new Rectangle();
}
return instance;
}
public static void setLen (double l){
len = l;
}
public static double getLen (){
return len;
}
public static void setWid (double w){
wid = w;
}
public static double getWid(){
return wid;
}
}
But, like #almas_shaikh said, it's easier to pass the object instance to the method.
Also, let me remind you that the word length is used by java to determine size of arrays and other objects, as getLength() method. You should use another name to length attribute and method to avoid conflicts.

Related

How to find the maximum's index?

I got this problem here. The index is int, but the program throws me double. I can't find the problem. There are a lot of geometric shapes, and they have center coordinates and the length of their side. I had to calculate the difference of the area and the circumstance, and then pick the largest number's index.
/Main class
package beadandó;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
Geom geom = new Geom();
try {
geom.read("input.txt");
System.out.println(geom.MaxKiv());
} catch (FileNotFoundException ex) {
System.out.println("File not found!");
System.exit(-1);
} catch (InvalidInputException ex) {
System.out.println("Invalid input!");
System.exit(-1);
}
}
}
/getDifference
package beadandó;
import java.util.ArrayList;
public abstract class GeometricShape {
private Point center;
double length;
private ArrayList<Double> difference;
public GeometricShape( Point center, double length) {
this.center = center;
this.length = length;
difference = new ArrayList<>();
}
public void setCenter(Point center) {
this.center = center;
}
public void setLength(double length) {
this.length = length;
}
public Point getCenter() {
return center;
}
public double getLength() {
return length;
}
public ArrayList<Double> getDifference() {
return difference;
}
public abstract double doMath();
}
/MaxKiv is the maximum finder
package beadandó;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class Geom {
private final ArrayList<GeometricShape> geometricShapes;
public Geom() {
geometricShapes = new ArrayList<>();
}
public void read(String filename) throws FileNotFoundException, InvalidInputException {
Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
int number = sc.nextInt();
while (sc.hasNext()) {
GeometricShape geometricShape;
int kind = sc.nextInt();
double x = sc.nextDouble();
double y = sc.nextDouble();
Point center = new Point(x, y);
double length = sc.nextDouble();
switch (kind) {
case 0:
geometricShape = new Circle(center, length);
break;
case 3:
geometricShape = new Triangle(center, length);
break;
case 4:
geometricShape = new Square(center, length);
break;
case 6:
geometricShape = new Hexagon(center, length);
break;
default:
throw new InvalidInputException();
}
geometricShapes.add(geometricShape);
}
}
public double MaxKiv() {
double max = 0;
int index =0;
for (int i = 0; i < geometricShapes.size(); ++i) {
if (max <geometricShapes.get(i).doMath()) {
max = geometricShapes.get(i).doMath();
index=i;
}
}
return index;
}
}
/Calculate the differences (there are many shapes, this is one of them)
package beadandó;
import static java.lang.Math.sin;
public class Hexagon extends GeometricShape {
public Hexagon(Point center, double length) {
super(center, length);
}
#Override
public double doMath() {
double circumfence=(3*(length*length)*sin(60));
double district=(6*length);
double difference=(circumfence-district);
return difference;
}
}
You have declared:
public double MaxKiv() {
So yes, obviously this gives you a double. To get an int instead, simply change the declaration to return an int:
public int MaxKiv() {
The value you are returning, index, is already declared an int, so this should be enough fix your issue.

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.

How do I leave a trail behind my animation? [duplicate]

This question already has answers here:
Create a Trailing line of blood behind a player
(2 answers)
Closed 6 years ago.
I have a program that takes information on two planets/bodies in space and animates their orbits around each other realistically. It works, though when I repaint, it clears the screen each time and does not leave a trail.
My problem is that I want to leave a trail, though any answer I can find online only explains how to get rid of a trail. However, I don't have that problem.
On other computers, I can leave out the super.paintComponent() in my paint method and that causes it to leave a trail, but on this computer, it doesn't do that, it seems to clear the screen automatically. So then how can I efficiently draw a trail behind my orbiting planets? My code follows.
JPanel class first:
import javax.swing.*;
import java.awt.*;
/**
* Created by chris on 3/2/16.
*/
public class SpacePanel2 extends JPanel{
private Body2[] planets;
public static final Dimension SCREENSIZE = Toolkit.getDefaultToolkit().getScreenSize();
public static double scale = 5e6; //m/p
public static Color[] colors = {Color.black, Color.red};
public SpacePanel2(Body2[] planets) {
this.planets = planets;
this.setPreferredSize(SCREENSIZE);
}
#Override
public void paint(Graphics g){
for (int i = 0; i < planets.length; i++) {
g.setColor(colors[i]);
int r = planets[i].getPixelRadius()/2;
int x = planets[i].getPixelX();
int y = planets[i].getPixelY();
g.fillOval(x, y, r, r);
}
}
}
Body class:
/**
* Created by chris on 3/2/16.
*/
public class Body2 {
private double mass; //in kilograms
private double radius; //in meters
private static final double GRAVITATIONAL_CONSTANT = 6.67408e-11;
private static final double AVERAGE_DENSITY = 5515; //kg/m^3
/**
* Movement variables
*/
private double dx; //in m/s
private double dy; //in m/s
private double x; //in m
private double y; //in m
public Body2() {
radius = 1;
mass = AVERAGE_DENSITY;
x = 0;
y = 0;
dx = 0;
dy = 0;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
public int getPixelX() {
return (int)((this.x-radius)/SpacePanel2.scale);
}
public int getPixelY() {
return (int)((this.y-radius)/SpacePanel2.scale);
}
public int getPixelRadius(){
return (int)(this.radius/SpacePanel2.scale);
}
public void setMass(double mass) {
this.mass = mass;
}
public void setRadius(double radius) {
this.radius = radius;
}
public void setDx(double dx) {
this.dx = dx;
}
public void setDy(double dy) {
this.dy = dy;
}
public void setX(double x) {
this.x = x;
}
public void setY(double y) {
this.y = y;
}
public void exertForce2(double diffY, double diffX, double F){
double dist = Math.sqrt(diffY*diffY + diffX*diffX);
double ratio = F / dist;
this.dy = this.dy + ratio*diffY/this.mass;
this.dx = this.dx + ratio*diffX/this.mass;
}
public void tick(double timeScale) {
x+=(dx/1000.0)*timeScale;
y+=(dy/1000.0)*timeScale;
}
public static double getForce(Body2 a, Body2 b){
double dX = a.getX() - b.getX();
double dY = a.getY() - b.getY();
double distance = Math.sqrt(Math.pow(dX,2)+Math.pow(dY,2));
return (a.getMass()*b.getMass()*GRAVITATIONAL_CONSTANT)/(distance*distance);
}
public static double getStandardMass(double radius){
return (4.0/3.0)*Math.pow(radius, 3) * Math.PI;
}
public double getDy() {
return dy;
}
public double getDx() {
return dx;
}
public static double predictCentripetalForce(Body2 sun, Body2 planet){
return Math.sqrt(getForce(planet, sun)*(sun.getY()-planet.getY())/planet.mass);
}
}
Main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* Created by chris on 3/2/16.
*/
public class MainSpace2 {
static JFrame frame;
static SpacePanel2 panel;
static int fps = 60;
static boolean getLarger = false;
static boolean getSmaller = false;
static Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
public static void main(String[] args) {
Body2[] test = new Body2[2];
Body2 sun = new Body2();
sun.setRadius(696300000);
sun.setMass(1.989e30);
sun.setX(getScope('x') / 2);
sun.setY(getScope('y') / 2);
sun.setDx(0);
sun.setDy(0);
test[0] = sun;
int literalSizeSun = (int)(sun.getRadius()/SpacePanel2.scale);
Body2 mercury = new Body2();
mercury.setRadius(24400000);
mercury.setMass(Body2.getStandardMass(mercury.getRadius()));
mercury.setDx(Body2.predictCentripetalForce(sun, mercury)*2);
mercury.setDy(0);
mercury.setX(sun.getX());
mercury.setY(sun.getY() + 2 * sun.getRadius());
test[1] = mercury;
int literalSizeMercury = (int)(mercury.getRadius()/SpacePanel2.scale);
frame = new JFrame();
frame.setPreferredSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new SpacePanel2(test);
frame.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyChar()) {
case '-':
getSmaller = true;
getLarger = false;
break;
case '=':
getLarger = true;
getSmaller = false;
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyChar()) {
case '-':
getSmaller = false;
break;
case '=':
getLarger = false;
break;
}
}
});
double timeScale = 60*24;
Timer time = new Timer((int) (1000.0 / fps), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
double F = Body2.getForce(test[0], test[1]);
double dY = test[1].getY() - test[0].getY();
double dX = test[1].getX() - test[0].getX();
test[0].exertForce2(dY, dX, F);
test[1].exertForce2(-dY, -dX, F);
for (int j = 0; j < test.length; j++) {
test[j].tick(timeScale);
}
panel.repaint(sun.getPixelX(), sun.getPixelY(), literalSizeSun, literalSizeSun);
panel.repaint(mercury.getPixelX(), mercury.getPixelY(), literalSizeMercury, literalSizeMercury);
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
time.start();
}
public static double getScope(char k) {
switch (k) {
case 'x':
return size.width * SpacePanel2.scale;
case 'y':
return size.height * SpacePanel2.scale;
default:
return 0;
}
}
}
Custom painting is done by overriding the paintComponent() method, not paint().
if you leave a continuous trail, once you do a 360 rotation you won't see any more animation, so I would think you need to clear the screen eventually.
If you want to leave a trail you can keep an ArrayList of Objects you want to paint. Then in the paintComponent() method you can iterate through the List. This will allow you to add/remove Object from the list so you can control the number of Objects you want to paint each animation.
Check out the DrawOnComponent example from Custom Painting Approaches for an example of this approach. So your animation logic would basically add a new Object (and potentially remove one once you reach a certain limit?) to the List. Then you just invoke repaint() on the panel and all the Objects will be painted.
You already have List to paint each planet. So each animation you would need to add the new location of each planet to the List.
Or, the link shows how you can paint to a BufferedImage. But this approach doesn't allow you to remove a painting once it is done. So it depends an your exact requirement which approach you use.

How to create an object from data in a file and assign it to an array?

I need to take information from a file and create them into objects and put them into an array so I can compare the areas of the objects and list in the array which object has the largest area and its location in the array.
I'm confused on how I take the information from the file and create each one into a object (circle or rectangle) and then assign that object into an array after it has been created. I think my other classes are fine, I'm just stuck on finishing the driver.
Normally, I would do something like Circle c1 = new Circle(); to create a new object, but how do I do that from a file with predefined information and assign it to an array?
Data:
“CIRCLE”, 1, “blue”, true
“RECTANGLE”, 1, 2, “blue”, true
“RECTANGLE”, 10, 2, “red”, true
“CIRCLE”, 2, “green”
“RECTANGLE”
“CIRCLE”
Driver:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("C:/Users/Charles/Desktop/GeometricObjectsData.txt"));
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
}
}
}
GeometricObject:
public abstract class GeometricObject {
//class variables
private String color;
private boolean filled;
//constructors
public GeometricObject() {
super();
color = "white";
filled = false;
}
public GeometricObject(String color, boolean filled) {
super();
this.color = color;
this.filled = filled;
}
//mutators
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
//user-defined methods
public abstract double getArea();
public abstract double getPerimeter();
#Override
public String toString() {
return super.toString() + " \tColor=" + this.getColor() + " \tFilled=" + this.isFilled();
}
}
Circle:
public class Circle extends GeometricObject {
//class variables
private double radius;
//constructors
public Circle() {
super();
radius = 1;
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
this.radius = radius;
}
//mutators
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//user-defined methods
#Override
public double getArea() {
//area of a circle
return (radius * radius * Math.PI);
}
#Override
public double getPerimeter() {
//perimeter of a circle
return (2 * radius * Math.PI);
}
#Override
public String toString() {
return super.toString() + "\nCircle: Radius=" + this.getRadius();
}
}
Rectangle:
public class Rectangle extends GeometricObject {
//class variables
private double height;
private double width;
//constructors
public Rectangle() {
super();
height = 1;
width = 1;
}
public Rectangle(double height, double width, String color, boolean filled) {
super(color,filled);
this.height = height;
this.width = width;
}
//mutators
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
//user-defined methods
#Override
public String toString() {
return super.toString() + "\nRectangle: Height=" + this.height + "\tWidth=" + this.width;
}
#Override
public double getArea() {
return (height * width);
}
#Override
public double getPerimeter() {
return (2 * height + 2 * width);
}
}
In your text file, you have special quotes around your shape items. This will make your life more difficult, so you should change that, if possible
Example of how to make objects (from your main method):
while (input.hasNext()) {
String line = input.nextLine();
System.out.println(line);
String[] parts = line.split(",");
if (parts[0].indexOf("Circle") != -1) {
Circle c = new Circle();
// ... parse the rest of the attributes to set up your circle
} else if ... // fill in the other shape cases
}

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