How to find the maximum's index? - java

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.

Related

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.

Drawing in class that extends javafx.scene.canvas.Canvas

I am trying to extend a java fx Canvas:
package com.kavricious.math;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import java.util.Random;
public class LPlotCanvas extends Canvas{
boolean grid = false;
boolean axes = true;
boolean ticks = true;
boolean startDrawn = false;
double xMin;
double xMax;
double yMin;
double yMax;
int density;
short canvasWidth = 800;
short canvasHeight = 800;
byte colorIndex = 0;
private GraphicsContext gc = null;
public LPlotCanvas(double xmin,double xmax, double ymin, double ymax){
xMin = xmin;
xMax = xmax;
yMin = ymin;
yMax = ymax;
density = 100;
setWidth(canvasWidth);
setHeight(canvasHeight);
gc = getGraphicsContext2D();
drawStart();
}
private void drawStart(){
System.out.println("drawing start");
if(gc == null)System.out.println("it null");
gc.setLineWidth(2);
gc.setStroke(Color.BLACK);
if(axes){
if(xMin<0.0&&xMax>0.0){
drawLine(gc,0,yMin-1,0,yMax+1);
}
if(yMin<0.0&&yMax>0.0){
drawLine(gc,xMin-1,0,xMax+1,0);
}
}
if(grid){
for(int i =(int)((xMin>0)?Math.floor(xMin):Math.ceil(xMin));i<xMax+1;i++){
gc.setLineWidth(0.25);
drawLine(gc,i,yMin,i,yMax);
}
for(int i =(int)((yMin>0)?Math.floor(yMin):Math.ceil(yMin));i<yMax+1;i++){
gc.setLineWidth(0.25);
drawLine(gc,xMin,i,xMax,i);
}
}
startDrawn = true;
}
public void showGrid(boolean b){
grid = b;
}
public void showAxes(boolean b){
axes = b;
}
public void showTicks(boolean b){
ticks = b;
}
public void setCanvasWidth(short width){
this.canvasWidth = width;
}
public void setCanvasHeight(short height){
this.canvasHeight = height;
}
private void plotPoint(double x,double y,Color color){
if(!startDrawn)drawStart();
gc.setFill(color);
gc.fillOval(convertX(x),convertY(y),5,5);
}
public void drawPolynomial(LPolynomial function)throws Exception{
if(!startDrawn)drawStart();
gc.setStroke(getNextColor(colorIndex));
double start = xMin;
double step = (xMax-xMin)/density;
for(int i=0;i<density;i++){
drawLine(gc,start+step*i,function.evaluateAt(start+step*i),start+step*(i+1),function.evaluateAt(start+step*(i+1)));
}
colorIndex++;
}
private void drawLine(GraphicsContext gc,double x1,double y1,double x2, double y2){
int nx1 = convertX(x1);
int ny1 = convertY(y1);
int nx2 = convertX(x2);
int ny2 = convertY(y2);
gc.strokeLine(nx1,ny1,nx2,ny2);
System.out.println("line drawn");
}
private int convertX(double in){
double widthOfPixel = (xMax-xMin)/canvasWidth;//how much space on the real number line is put into one pixel
return (int) Math.floor((in-xMin)/widthOfPixel);//how much greater than left side DIVIDED by pixel size -> how many pixels away from left side
}
private int convertY(double in){
double heightOfPixel = (yMax-yMin)/canvasHeight;
return canvasHeight - (int) Math.floor((in-yMin)/heightOfPixel);
}
public Color getNextColor(byte i){
switch(i){
case 0: return Color.rgb(255,0,0);//red
case 1: return Color.rgb(0,200,0);//lime
case 2: return Color.rgb(0,0,235);//blue
case 3: return Color.rgb(255,255,0);//yellow
case 4: return Color.rgb(255,50,255);//magenta/fuchsia
case 5: return Color.rgb(255,165,0);//orange
case 6: return Color.rgb(0,235,235);
case 7: return Color.rgb(107,30,119);
case 8: return Color.rgb(0,100,0);
default: Random rand = new Random();
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
return Color.rgb(r,g,b);
}
}
}
and then call it in another application:
package com.kavricious.math;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;
import java.util.ArrayList;
public class LPlotter2 extends Application{
private ArrayList<LPolynomial> functions;
public static void main(String[] args){
launch(args);
}
#Override
public void start(Stage ps){
this.functions = new ArrayList<LPolynomial>();
LPolynomial[] funcs = new LPolynomial[]{new LPolynomial(2.3,3.4,2.2,1.1),new LPolynomial(0,1,-2.3),new LPolynomial(1,2),new LPolynomial(2,2,2.3,1,0.4)};
for(LPolynomial f: funcs){
this.functions.add(f);
}
ps.setTitle("LPlotter");
StackPane layout = new StackPane();
LPlotCanvas canv = new LPlotCanvas(-10,10,-10,10);
for(LPolynomial function : functions){
try{
canv.drawPolynomial(function);
}catch(Exception e){System.out.println("an exception wad caught");e.printStackTrace();}
}
layout.getChildren().add(canv);
ps.setScene(new Scene(layout,800,800));
ps.show();
}
}
(In the above code I have tried putting the for loop that draws the polynomials in every position possible after the LPlotCanvas is initialized, and the same result occurs.)
but then I run it and see nothing:
This is what it should look like (created without extension).
So what is wrong?

IndexOutofBounds exception creating a maze

I'm working on a school assignment where I am supposed to create a maze from a textfile. My problem is creating the maze. I know it's probably an easy fix, but I am really stuck and need to get this done.. Any suggestions?
package application;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javafx.application.Application;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
public class Main extends Application {
LabyrintRute[][] Labyrint;
int X;
int Y;
int startx;
int starty;
Spiller spilleren;
int sizeX;
int sizeY;
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
Spiller spilleren = new Spiller(startx, starty);
filLeser();
root.add(spilleren.getUtseende(), spilleren.getxPossisjon(), spilleren.getyPossisjon());
for(int x = 0; x<X; x++){
for(int y = 0; y<Y; y++){
root.add(Labyrint[x][y].getUtseende(), x, y);
}
}
Scene scene = new Scene(root, X*10, Y*10);
scene.setOnKeyPressed(new FilLytter(this));
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void filLeser() {
String teksten = "";
File fila;
int rad = 0;
FileChooser filvelger = new FileChooser();
filvelger.setTitle("Åpne en tekstfil");
filvelger.getExtensionFilters().add(new ExtensionFilter("Text Files", "*.txt"));
fila = filvelger.showOpenDialog(null);
try (Scanner filleser = new Scanner(fila)) {
X = filleser.nextInt();
Y = filleser.nextInt();
teksten = filleser.nextLine();
Labyrint = new LabyrintRute [X][Y];
while (filleser.hasNext()) {
teksten = filleser.nextLine();
for (int i = 0;i< X;i++) {
char tegn = teksten.charAt(i);
switch (tegn) {
case '#':
Labyrint[i][rad] = new Vegg(i, rad);
break;
case ' ':
Labyrint[i][rad] = new Gang(i, rad);
break;
case '-':
Labyrint[i][rad] = new Utgang(i, rad);
break;
case '*':
Labyrint[i][rad] = new Gang(i, rad);
startx = i;
starty = rad;
break;
}
rad++;
}
}
} catch (FileNotFoundException e) {
System.out.println("Kan ikke åpne fila!");
e.printStackTrace();
}
}
public void flyttSpiller(int deltax, int deltay) {
int nyx = spilleren.getxPossisjon() + deltax;
int nyy = spilleren.getyPossisjon() + deltay;
Labyrint[nyx][nyy].flyttHit(spilleren);
}
public static void main(String[] args) {
launch(args);
}
}
The "Vegg"(wall) class:
package application;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
public class Vegg extends LabyrintRute {
private Node utseende;
public Vegg(int xKoordinat, int yKoordinat) {
super(xKoordinat, yKoordinat);
utseende = new Rectangle(10, 10, Color.MEDIUMPURPLE);
}
#Override
public void flyttHit(Spiller spilleren) {
//spilleren.setxPossisjon(getxKoordinat());
//spilleren.setyPossisjon(getyKoordinat());
}
#Override
public Node getUtseende() {
return utseende;
}
}
Abstract class:
package application;
import javafx.scene.Node;
public abstract class LabyrintRute {
private int xKoordinat;
private int yKoordinat;
public LabyrintRute(int xKoordinat, int yKoordinat) {
this.xKoordinat = xKoordinat;
this.yKoordinat = yKoordinat;
}
public int getxKoordinat() {
return xKoordinat;
}
public int getyKoordinat() {
return yKoordinat;
}
public abstract void flyttHit(Spiller spilleren);
public abstract Node getUtseende();
}
I also have a "Gang" (passage), and a "Utgang" (exit) class. They are similiar to the "Vegg" class.
Would really appreciate inputs! Sorry for the norwegian code..
When you read the file and create the lab, your variable rad is incremented in a loop that goes to from 0 to X-1. However, you use it to index the Y dimension. If X > Y, you will run out of bounds there.
Since your code does not fully reveal the rules of the file and how the lab can be formed,I cannot provide a fix directly.
I think you most probably need some kind of nested loop. Maybe you should keep and increment i with the nextLine's and have the inner loop somehow like for (int rad = 0; rad < Y; rad++) but again, it's impossible for me to say without further inside.

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.

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