Why is my smaller method giving me an error - java

This is my first class called class circle:
public class circle
{
//circle class begins
//declaring variables
public double circle1;
public double circle2;
public double circle3;
public double Xvalue;
public double Yvalue;
public double radius;
private double area;
//Constructor
public circle(int x,int y,int r)
{//constructor begins
Xvalue = x;
Yvalue = y;
radius = r;
}//constructor ends
//method that gets the area of a circle
public double getArea ()
{//method getArea begins
area = (3.14*(this.radius * this.radius));
return area;
}//getArea ends
public static smaller (circle other)
{
if (this.area > other.area)
{
return other;
else
{
return this;
}
//I'm not sure what to return here. it gives me an error( I want to return a circle)
}
}//class ends
}
This is my tester class:
public class tester
{//tester begins
public static void main(String args [])
{
circle circle1 = new circle(4,9,4);
circle circle2 = new circle(4,7,6);
c3 = c1.area(c2);
System.out.println(circle1.getArea());
//System.out.println(
}
}//class tester ends

The smaller method should have a return type. Also the this keyword cannot be used in a static method. i.e. the method will not have access to the instance of Circle. This make sense given what the method name smaller implies - it compares the current instance of Circle with another passed in.
public Circle smaller(circle other) {
if (this.area > other.area) {
return other;
} else {
return this;
}
}
To use:
Circle smallerCircle = circle1.smaller(circle2);
Aside: Java naming conventions show that class names start with an uppercase letter to give Circle.

Area is unassigned when you make the operation :
c3 = c1.area(c2);
You need to make the GeArea() call before you can use the area field of the class.
So for example:
circle circle1 = new circle(4,9,6);
circle circle2 = new circle(4,7,6);
circle2.area = c1.getArea();
That is assuming that the c3 var you're trying to assign to has been instantiated as a circle.

You simply forgot a closing brace
if (this.area > other.area)
{
return other;
} //You forgot this brace and confused the compiler
else
{
return this;
}

Related

Must implement abstract method

This is using Processing 3.5, not every java thing works the same here.
The Bird class is giving me the error saying it needs to implement call(). Isn't it already under the main? I'm not experienced with interfaces so I don't know what exactly is going on here.
public interface FuncCall<A> {
A call();
}
class Bird implements FuncCall{
//Error here ^
//The type FuncCallTest.Bird must implement the inherited abstract method FuncCallTest.FuncCall.call()
//Is this not implemented already under main?
float x, y, size;
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Bird(float x, float y, float size){
this.x = x;
this.y = y;
this.size = size;
}
public void main(String[] args){
FuncCall<Float> getX = new FuncCall<Float>(){
#Override
public Float call(){
return x;
}
};
FuncCall<Float> getY = new FuncCall<Float>(){
#Override
public Float call(){
return y;
}
};
FuncCall<Float> getSize = new FuncCall<Float>(){
#Override
public Float call(){
return size;
}
};
inputs.add(getX);
inputs.add(getY);
inputs.add(getSize);
}
}
class Pol {
ArrayList<FuncCall<Float>> inputs = new ArrayList<FuncCall<Float>>();
public Pol(ArrayList<FuncCall<Float>> inputs){
this.inputs = inputs;
}
//public float call(ArrayList<FuncCall<Float>> arr, int index){
//return arr.get(index).call();
//}
//How do I do this? Do I need to implement the interface here as well? Because if so same error as on Bird
}
I'll also stick this extra bit on the end here.
System.out.println(pol.call(pol.inputs, 1));
Does will that work? It doesn't error before compiling.
I appreciate any help. Please ask if something doesn't make sense as I'm still new to stack and not the best with java. :)
main file :
void setup(){
Bird bird = new Bird(1.2, 3.2, 7.5);
Pol pol = new Pol(bird.inputs);
System.out.println(pol.call(pol.inputs, 1););
}
First of all you could skip your FuncCall interface and use Java's Supplier functional interface and just add these Suppliers respectively method references of your class objects getters to the list.
Another approach is to provide an interface or abstract class that has getters and/or member variables for x, y and size and use this interface or abstract class as type parameter for the list.
With Suppliers:
This is closer to your example and requires less changes in
your code.
The second option with an interface changes your Pol class
completely and I am not sure if this is acceptable for you.
´
public class Bird {
private float x;
private float y;
private float size;
public Bird(float x, float y, float size) {
//set your members here
}
public Float getX() {
return this.x;
}
public Float getY() {
return this.y;
}
public Float getSize() {
return this.size;
}
}
´
Then the Pol class
´
public class Pol {
private final List<Supplier<Float>> inputs;
public Pol(List<Supplier<Float>> inputs) {
this.inputs = inputs;
}
public Float call(int index) {
return this.inputs.get(index).get();
}
}
´
And your main should look like
´
public static int main(String[] args) {
Bird bird = new Bird(1.0f, 1.0f, 2.5f);
Pol pol = new Pol(Arrays.asList(bird::getX,
bird::getY, bird::getSize));
Float birdsSize = pol.call(2);
return 0;
}
´

choosing specific object in an array of objects

public abstract class ShapeClass {
private double area;
CONSTRUCTORS
MUTATORS, ACCESSORS
public abstract double calcArea();
}
public class CircleClass extends ShapeClass {
private int diameter;
private double area;
public CircleClass() {
super();
diameter = 10;
}
public CircleClass(CircleClass inCircle) {
super(inCircle);
diameter = inCircle.getDiameter();
}
public CircleClass(int inDiameter) {
setDiameter(inDiameter);
area = calcArea();
super.setArea(area);
}
public void setDiameter(int inDiameter) {
if(validateInt(inDiameter)) {
diameter = inDiameter;
} else {
throw new IllegalArgumentException("invalid diameter");
}
}
public int getDiameter() {
return diameter;
}
public boolean equals(int inDiameter) {
return(diameter == inDiameter);
}
public boolean equals(Object inObj) {
boolean same = false;
if(inObj instanceof CircleClass) {
CircleClass inCircle = (CircleClass)inObj;
if(super.equals(inCircle)) {
if(diameter == inCircle.getDiameter()) {
same = true;
}
}
}
return same;
}
public String toString() {
return (" area of circle is: " + super.toString());
}
private boolean validateInt(int inDiameter) {
boolean valid = false;
if (inDiameter>0) {
valid = true;
}
return valid;
}
private boolean validateReal(double inArea) {
boolean valid = false;
if(inArea>0.0) {
valid = true;
}
return valid;
}
#Override
public double calcArea() {
double radius;
radius = ((double) diameter) / 2.0;
area = Math.PI * radius * radius;
return area;
}
}
This is my code for a ShapeClass. I have two other classes Rectangle and Triangle, they're pretty much the same as the CircleClass.
In another class i'm assigning the ShapeClass objects in an array.
if I do that it'll be something like shape[3] = {Shape Object,Shape Object,Shape Object}. I don't know if that's right, I'm new to java. Sorry if there's any confusion.
My question is if I do that how do I distinguish what object is Circle, Rectangle or Triangle? When I want to print out a circle object only?
Thanks for the help.
You can check by using instanceof :
if(shape[0] instanceof Circle){
// do something
}
So there is an operator in java - instance of:
if(shapeObject instanceof Circle){
//print
}
so you can use it to distinguish objects by type. Also as for your question whether it's correct: You can use this approach with creating array of parent object type and putting children in it. After that, if you call toString method on each object from that array specific implementation of that method will be invoked. For example if there is Circle object in this array and there is overridden toString method in it then after calling toString on object from array of ShapeObject specific implementations will be invoked.
Try like this,
for(int i = 0; i < shapeArray.length; i++){
if(shapeArray[i] instanceof CircleClass){
// print circle here
}
}
You have 2 options:
// Solution 1: prits out all instances of Circle, basically also all subclasses of Circle
for (ShapeClass shape : shapes) {
if (shape instanceof CircleClass)
System.out.println(shape.toString());
}
// Solution 2: Matches exact class
for (ShapeClass shape : shapes) {
if (shape.getClass().equals(CircleClass.class))
System.out.println(shape.toString());
}
The above solutions will solve the task you asked about. But maybe the information below will be userful for you:
What if you want to print out the names of each shape, how to distingush them in this case?
Let's say we have 3 shapes:
public class Shape {
public void print() {
System.out.println("Shape is printed");
}
}
public class Triangle extends Shape {
#Override
public void print() {
System.out.println("Triangle is printed");
}
}
public class Circle extends Shape {
#Override
public void print() {
System.out.println("Circle is printed");
}
}
This code will print exactly what you need, because you defined the same function for all of the shapes, overriding it in child classes, and the appropriate function will be called based on object type determined at the runtime:
for (Shape shape : shapes) {
shape.print();
}

Constructor method only working while other variables are static and also not working for first object

I have two classes, one called Soldier, and one called Battlefield, the soldier can spawn at any location that is within the battle field dimensions that are specified by the parameter of the battle field
the variables that put the Soldier object on x and y axis are:
private double xPos;
private double yPos;
those are within the Soldier class
the method for spawning the Soldier object on the battle field are
public Soldier(double speed) {
this.speed = speed;
xPos = (int) (Math.random() * Battlefield.getX());
yPos = (int) (Math.random() * Battlefield.getY());
}
And within the battle field class
private static double x;
private static double y;
public static double getY() {
// TODO Auto-generated method stub
return y;
}
public static double getX() {
// TODO Auto-generated method stub
return x;
}
Main Method,
public class Battle {
//Main method where three battles are run.
public static void main(String[] args) {
Battlefield k = new Battlefield(100, 100);
Battlefield b = new Battlefield(100, 100);
Battlefield c = new Battlefield(100, 100);
}
}
the problem I am having is this way of doing it is causing the first object to not have any coordinates and everything after that seems fine, but why?
From the main class, it looks like you want each Battlefield to have its own state... So don't make Battlefield.x and Battlefield.y static or else they will all be the same.
Where is the constructor for Battlefield?

A new object seems to change the fields of previous objects

I'm writing a game which contains elevators as an obstacle. An elevator spawns either left or right of the screen and has a random chance to be an ascending elevator or a descending elevator. It looks like this:
public class Elevator extends WorldObject {
public static boolean ascending;
public Elevator(int screenHeight, int xPos) {
super(xPos, screenHeight, 0, 0);
ascending = new Random().nextBoolean();
}
static public boolean isAscending(){
return ascending;
}
}
WorldObject from which it extends looks like this:
public class WorldObject {
protected float posX;
protected float posY;
protected float velX, velY;
public float getPosX() {
return posX;
}
public void setPosX(float posX) {
this.posX = posX;
}
public float getPosY() {
return posY;
}
public void setPosY(float posY) {
this.posY = posY;
}
public float getVelX() {
return velX;
}
public void setVelX(float velX) {
this.velX = velX;
}
public float getVelY() {
return velY;
}
public void setVelY(float velY) {
this.velY = velY;
}
public WorldObject(float posX, float posY, float velX, float velY) {
this.posX = posX;
this.posY = posY;
this.velX = velX;
this.velY = velY;
}
}
Every 5 seconds an elevator will be created and added to an ArrayList of Elevators like so:
if (timeToElevator > 5.0f) {
timeToElevator = 0;
Elevator elevator = new Elevator((int) screenHeight, (int) generateElevatorXPos());
Sprite eSprite = new Sprite(elevatorTexture);
eSprite.setOrigin(0, 0);
elevators.add(elevator);
elevatorSprites.add(eSprite);
}
I then check for collisions in each elevator with the player, remove it if it goes out of bounds and if neither of these happen I update the position of the elevator object:
public static void calculateElevatorCollisions() {
int counter = 0;
for (Iterator<Elevator> i = elevators.iterator(); i.hasNext(); ) {
Elevator item = i.next();
if (item.getPosY() < -100) {
//remove elevator
} else if (..collision..) {
//collision
} else {
item.setVelY(item.isAscending() ? -5 : 5);
item.setPosY(item.getVelY() + item.getPosY());
elevatorSprites.get(counter).setPosition(item.getPosX(),
item.getPosY());
counter++;
}
My issue is whenever a new Elevator is created all current Elevators change their direction to the direction of the new Elevator. So suppose I have two ascending elevators being drawn, whenever my third elevator is created to be descending, the other two previously ascending elevators now ascend!
What's causing this?
This is your problem:
public static boolean ascending;
^^^^^^
static means "This is a class field that is shared by all objects". So if you changed the field from one object, it will be noticed across all objects of that type.
Removing it to make ascending an instance field means that each instance of Elevator will have its own copy which it can modify by itself without changing other instances' copy.
Change
public static boolean ascending;
To
public boolean ascending;
When you set a variable as static it is a class variable, not an instance variable. Class variables are variables that are shared across all instances of an object, whereas instance variables are specific to that instance of the object.
As I can't comment yet (rep), I want to make another note:
You are practicing encapsulation using the getter for ascending, isAscending(); however, the field you are encapsulating is public, making it accessible from all scopes.
It's good practice to keep encapsulated fields private.
Also, it seems as if everyone is only stating that the field be changed to a non-static variable; however, the method is still static, even though it is actually an instance method as well!
Resulting changes needed:
public static boolean ascending;
becomes
private boolean ascending;
...and...
static public boolean isAscending()
becomes
public boolean isAscending()

hierarchical inheritance of abstract class with concrete method gives "<identifier> expected" error in Java

I am trying to run the following simple code,
public abstract class Shape{
abstract double area();
abstract double circumference();
public void show()
{
System.out.println("Area = "+area());
System.out.println("Circumference = "+circumference());
}
}
public class Circle extends Shape{
double r;
public double area()
{
return 3.14*r*r;
}
double circumference()
{
return 2*3.14*r;
}
Circle(double radius)
{
r=radius;
}
}
public class Rectangle extends Shape{
double x,y;
double area()
{
return x*y;
}
double circumference()
{
return 2*(x+y);
}
Rectangle(double length, double width)
{
x = length;
y = width;
}
}
public class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
But I keep getting identifier expected error from Java compiler. What am I doing wrong. Everything is public and there seems to be no syntax error. Please help.
This is the problem:
class Geometry
{
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Your final statement doesn't declare a variable - it's just a statement. That needs to belong in an initializer block, constructor or method. For example:
public class Geometry {
public static void showCircle() {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}
Note that this has nothing to do with inheritance - this code will give the same problem:
class Test {
System.out.println("Oops");
}
Your call to r.show(); is not in a code block. I suspect you intended to place this is a main method
public static void main(String... args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
Add the main method:
public class Geometry
{
public static void main(String[] args) {
Circle r = new Circle(2.22);
Rectangle s = new Rectangle(2.33, 3.44);
r.show();
}
}

Categories