java.lang.IncompatibleClassChangeError: Implementing Utility class - java

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;
}
}

Related

How To Use Methods With Array In 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[].

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.

Cannot find symbol in method changeRecL but declared in main method

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.

How to divide string (x1,y1)(x2,y2) format

how to divide string (x1,y1)(x2,y2) format
for example String is (100,200) (300,600) and i am creating objects(point)
class point{
int x;
int y;
}
i tried using StringTokenizer but this is not the proper way.
I would do something like this -
public static class Point {
public Point(int x, int y) {
this.x = x;
this.y = y;
}
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String toString() {
return "(" + String.valueOf(x) + ", "
+ String.valueOf(y) + ")";
}
public static Point[] fromString(String in) {
if (in == null) {
return null;
}
List<Point> al = new ArrayList<Point>();
int p = 0;
for (;;) {
int openPos = in.indexOf('(', p);
if (openPos > -1) {
int closePos = in.indexOf(')', openPos + 1);
if (closePos > -1) {
String str = in.substring(openPos + 1,
closePos);
String[] t = str.split(",");
p = closePos + 1;
if (t.length != 2) {
continue;
}
al.add(new Point(Integer.valueOf(t[0]
.trim()), Integer.valueOf(t[1].trim())));
} else {
break;
}
} else {
break;
}
}
return al.toArray(new Point[al.size()]);
}
}
public static void main(String[] args) {
Point[] pts = Point
.fromString("(100,200) (300,600)");
System.out.println(Arrays.toString(pts));
}
Which, when I run it, outputs -
[(100, 200), (300, 600)]
You can create Point objects from the String as shown below:
public class Sample {
static List<Point> points = new ArrayList<Point>();
public static void main(String[] args) {
String s = "(100,200) (300,600)";
toPoints(s.replaceAll("[(),]", " "));
for (Point i : points)
System.out.println("points = " + i);
}
private static void toPoints(final String value) {
final Scanner scanner;
scanner = new Scanner(value);
while (scanner.hasNextInt()) {
points.add(new Point(scanner.nextInt(), scanner.nextInt()));
}
}
}
Trim leading/trailing brackets and split on bracket pairs, then for each x/y set, split on comma:
for (String pair : str.replaceAll("^\\(|\\)$", "").split("\\)\\s*\\(")) {
int x = Integer.parseInt(pair.split(",")[0]);
int y = Integer.parseInt(pair.split(",")[1]);
Point point = new Point(x, y);
// do something with point
}

Categories

Resources