Hi I am trying to write this piece of code about physics but have a problem.
In fact two problems:
1.the formula for gravitation its throwing a error about using the field .class
2.I want to declare the types of individual variables in a element
I think its clearer if I show the source code:
public class Main
{
public static void main(String[] args) {
}
abstract class Gravitation{
public abstract int Gravitation(int mass[],int dist,int force);
}
class PhySyst{
public int mass;
public int wt;
public float smallG = 9.8f;
//this is the posible value of charge
enum Charge{Positive,Negative,PositiveCoulumb,NegativeCoulumb,IsNegative,IsPositive};
}
class Earth extends Gravitation{
//stores acceleration due to gravity
public float smallG = 9.8f;
//the raduis of earth is needed in the physics formula for distance
public float GravityPressure = 6.67f;
public float raduisofEarth = 6371f;
//this finds the gravation using newtons principles
public int Gravitation(int mass[],int dist,int force)
{
force = (GravityPressure * mass[])/(dist * dist);
return force;
}
}
}
the error is this:
Main.java:32: error: '.class' expected
force = (GravityPressure * mass[])/(dist * dist);
^
1 error
Thanks for reading :)
Couple of Fixes here:
Constants should be static final (#constant).
Gm1m2/r2, formula so rather than array you should pass 2 input params (m1 and m2).
As multiplication is operation for number not array (mass[]).
Enum should be defined in public class or in static class.
As the force can be float, so change the return type to float from current int.
#JsonIgnoreProperties(ignoreUnknown = true)
class Category {
abstract class Gravitation {
public abstract float getGravitationalForce(int mass1, int mass2, int dist);
}
//this is the possible value of charge
enum Charge {
Positive, Negative, PositiveCoulumb, NegativeCoulumb, IsNegative, IsPositive
};
class PhySyst {
public int mass;
public int wt;
public float smallG = 9.8f;
}
class Earth extends Gravitation {
//stores acceleration due to gravity
public static final float SMALL_G = 9.8f; #constant
//the radius of earth is needed in the physics formula for distance
public static final float GRAVITATIONAL_PRESSURE = 6.67f; #constant
public static final float RADIUS_OF_EARTH = 6371f; #constant
//this finds the gravitation using newtons principles
public float getGravitationalForce(int mass1, int mass2, int dist) {
return (GRAVITATIONAL_PRESSURE * mass1 * mass2) / (dist * dist);
}
}
}
Related
I'm working on a tiny exercise java program that calculates circle and square (classes) area, that implements surface (interface) which has a method called area(). A requirement is that I have to implement a class called SumArea that has a generic method called calcArea() that receives Circle circ[] and Square square[] arrays and executes area calculation.
Program structure:
-> UseSumArea.java (main method)
-> Surface.java (interface)
-> Square.java (class that implements Surface.java)
-> Circle.java (class that implements Surface.java)
-> SumArea.java (class that executes calcArea() method)
UseSumArea.java
public class UseSumArea {
public static void main(String[] args) {
Square square[] = { new Square(2.0), new Square(5.0) };
Circle circ[] = { new Circle(3.0), new Circle(2.0) };
Surface surf[] = new Surface[square.length + circ.length];
surf[0] = square[0];
surf[1] = square[1];
surf[2] = circ[0];
surf[3] = circ[1];
SumArea sum = new SumArea();
System.out.println("Square's sum area = " + sum.calcArea(square));
System.out.println("Circle's sum area = " + sum.calcArea(circ));
System.out.println("Surface's sum area = " + sum.calcArea(surf));
}
}
Surface.java
public interface Surface {
public double area();
}
Square.java
public class Square implements Surface {
private double area;
private double side;
public Square(double l) {
this.side = l;
area();
}
#Override
public double area() {
return this.area = (this.side)*(this.side);
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
}
Circle.java
public class Circle implements Surface {
private double area;
private double radius;
public Circle (double r) {
this.radius = r;
area();
}
#Override
public double area() {
return area = (((this.radius)*(this.radius))*(Math.PI));
}
public double getRadius() {
return radius;
}
public void setRadius(double raio) {
this.raio = raio;
}
public double getArea() {
return area;
}
public void setArea(double area) {
this.area = area;
}
}
SumArea.java
public class SumArea {
private double area;
public <T> double calcArea(T[] t) { //generic method that receives Square and Circle arrays
double arrayArea = 0;
for (T a : t) {
arrayArea = arrayArea+(a.area());
}
return this.area = arrayArea;
}
}
My doubt is over this SumArea's code snippet:
arrayArea= arrayArea+(a.area());
How can I access the area() method of each Circle and Square objects inside this generic method?
You need to bound the type variable:
public <T extends Surface> double calcArea(T[] t) {
or just declare the parameter as an array of Surfaces:
public double calcArea(Surface[] t) {
Note that the latter is preferable because generics and arrays don't play very nicely together. If you were to need to have a type variable for other reasons, it would be advisable to change to a Collection, or similar:
public <T extends Surface> double calcArea(Collection<T> t) {
(And, as a minor matter of preference, I would use S rather than T to name a type variable which extends Surface)
Since the problem in regard to generic types is already addressed by Andy Turner, I just want to add a suggestion related to the class design.
I think there is a bit of redundancy in how these classes were designed. You need to create an instance of SumArea in order to do the calculation. And the result of the last of the last calcArea() method call will be stored in this object (let's assume that this calculation is far more complex and CPU-consuming).
But do we really need to store somewhere else the value is already returned by the method? In this case, the idea to cash the history of calculations (as a single variable or as a collection of values) doesn't seem to be useful because it can't be reused without knowing which objects were involved in the calculation.
And without storing the result this method will not be bound to a state, i.e. it has to be static. And since interfaces can have static methods, instead of creating a utility class for that purpose it could be placed in the Surface interface. Like that.
public interface Surface {
public double area();
public static <T extends Surface> double calcArea(T[] t) { // generic method that receives Square and Circle arrays
double arrayArea = 0;
for (T a : t) {
arrayArea += a.area();
}
return arrayArea;
}
}
Note that static behavior declared in interfaces in contrast to classes could be invoked only by using the name of an interface:
System.out.println("Circle's sum area = " + Surface.calcArea(circ));
Also note that it makes sense for both classes to have a field area inside the classes Circle and Square only if other fields will be declared as final, i.e. they must be initialed only one during the object construction and setters become unnecessary.
In this case (assuming that radius has been declared as final and is being validated when assigned so that reduce > 0) method area() will look like this:
#Override
public double area() {
if (area > 0) { // `0` is a default value for instance variables
return area; // reusing already calculated value
}
return area = radius * radius * Math.PI;
}
And there mustn't be two methods area() and getArea() leave either one or another.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
public class Main {
public static void main(String[] args) {
shape[] myShapes = new shape[3];
myShapes[0] = new cube(3);
myShapes[1] = new Sphere(2);
myShapes[2] = new Cylinder(3, 4);
for (shape: myShapes)
System.out.println()
}
}
class cube extends shape {
public double side;
public double newSide;
public double volume;
public double surface;
public cube(double side) {
this.side = side;
}
public void cubeVolume(){
volume = Math.pow(side,3);
System.out.println (volume);
}
public void cubeSurface(){
surface = Math.pow(side,2) * 6;
System.out.println (surface);
}
}
abstract class shape{
protected double volume;
protected double surface;
}
public class Sphere extends shape {
public double radius;
public double volume;
public double area;
public double i = 4;
public double j = 3;
public Sphere(double radius) {
this.radius = radius;
}
public void sphereVolume(){
volume = i/j * Math.PI * Math.pow(radius,3);
System.out.println(volume);
}
public void surfaceArea(){
area = 4 * Math.PI * Math.pow(radius,2);
System.out.println(area);
}
}
public class Cylinder extends shape{
public double radius;
public double height;
public double cylinderVolume;
public double cylinderArea;
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public void surface(){
cylinderArea = 2 * Math.PI * radius * height;
System.out.println(cylinderArea);
}
public void volume(){
cylinderVolume = Math.PI * Math.pow(radius, 2) * height;
System.out.println(cylinderVolume);
}
}
I do not think the title encompasses my question well. I am instantiating a new object and storing that object within the array myShapes. The class for each object has a method to calculate the surface area and volume. I need to call on all these methods, and I believe this can be done with a for loop, but I am not sure how. I am completely stumped.
Add abstract methods to your superclass:
abstract class Shape {
// Note: No fields
public abstract double surfaceArea();
public abstract double volume();
}
Implement them in your subclasses, eg for Cylinder:
public class Cylinder extends Shape {
// radius and height fields and constructor not shown
public double surfaceArea() {
return 2 * Math.PI * radius * height;
}
public double volume() {
return Math.PI * Math.pow(radius, 2) * height;
}
}
Then print them in your loop:
for (shape : myShapes) {
System.out.println("Surface area = " + shape.surfaceArea + ", volume = " + shape.volume());
}
Note that you don't want to print inside the methods - that's a rendering issue and should be done by the caller if appropriate. For example, you wouldn't want lots of output if you were just doing calculations and comparisons of shapes.
Also, it greatly helps readability if you follow Java Naming Conventions, especially classes should be SentenceCase and variables/parameters camelCase, so call your classes Shape instead of shape, Cube instead of cube etc.
If you don't have common fields, prefer an interface over an abstract class for the supertype.
If your storing your objects inside a shape[] array then, you need to make sure to define
volume() & surfaceArea() as abstract methods in your shape class so, that each of your shapes (Cylinder, Sphere, etc.) will then be able to override and implement. They need to be named the same as well.
I am trying to write a 'Cup' class which implements the Comparable interface.
My code:
class Cup<T> implements Comparable<T>{
public T radius;
public T height;
public Cup(T radius, T height){
this.radius = radius;
this.height = height;
}
public double getVolume(){
return (double) radius * (double) radius* (double) height* 3.14 ; // throwing error
}
public int compareTo(Object cup){
if(getVolume()== ((Cup) cup).getVolume()){ // cannot access java.lang.Comparable
return 0;
}
else if(getVolume() > ((Cup) cup).getVolume()){
return 1;
}
else if(getVolume() < ((Cup) cup).getVolume()){
return -1;
}
return -2;
}
}
class test{
public static void main(String[] args) {
Cup<Integer> mycup = new Cup<Integer>(5,5);
Cup<Integer> momscup = new Cup<Integer>(7,7);
mycup.compareTo(momscup);
}
}
But the program throws error stating:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Double.
I am NOT trying to cast to Double, but to double. Why is it throwing the error?
Thanks
I am NOT trying to cast to Double, but to double. Why is it throwing the error?
The root of your problem is that the static type of T is Object not Integer. So the compiler has determined that the following path may work:
Cast the object's actual type to Double (which requires a runtime check)
Unbox the Double to a double.
The problem is that Integer cannot be cast to Double.
The best solution is this:
class Cup<T extends Number> implements Comparable<T> {
...
public double getVolume(){
return radius.doubleValue() * radius.doubleValue()
height.doubleValue() * Math.PI;
}
which is statically type-safe (modulo any unsafe conversions that you might do elsewhere).
Note that if T was replaced by Integer, the compiler would use a different path for the conversion:
Unbox the Integer to an int.
Widen the int to a double.
Depending on exactly how you wrote the πr2h expression, the type casts may be unnecessary.
By what you are doing is actually implicitly adding a cast to Double and because of this you are getting the exception.
I'd suggest you few changes after which your class looks like this:
class Cup<T extends Number> implements Comparable<Cup<T>> {
public T radius;
public T height;
public Cup(T radius, T height) {
this.radius = radius;
this.height = height;
}
public double getVolume() {
return radius.doubleValue() * radius.doubleValue() * height.doubleValue() * 3.14;
}
#Override
public int compareTo(Cup<T> cup) {
return Double.compare(getVolume(), cup.getVolume());
}
}
Closely look how I've changed the compareTo method and the getVolume method to make it more readable.
And after these changes you don't get when running the test:
class test {
public static void main(String[] args) {
Cup<Integer> mycup = new Cup<>(5, 5);
Cup<Integer> momscup = new Cup<>(7, 7);
mycup.compareTo(momscup);
}
}
The following are the changes that I'd suggest you so that you can learn.
From Effective Java Item 31, you should use bounded wildcards to increase the API flexibility. (Read the generics chapter from Effective Java, it will be highly helpful)
Use Double.compare, it's a convenient method already given to do what exactly you want.
Use #Override if you are overriding a method.
Cup<Integer> mycup = new Cup<>(5, 5); While initialization you again don't need to mention Integer on the right-hand side. (This can be done if you are using JDK 7 or higher)
radius and height properties are defined as T, but you cast them to double, you should declare them as double or make the Generic type of the class extends Number which is the abstract parent class of Double and Integer
class Cup<T extends Number> {
public T radius;
public T height;
public Cup(T radius, T height) {
this.radius = radius;
this.height = height;
}
public double getVolume() {
return radius.doubleValue() * radius.doubleValue() * height.doubleValue() * 3.14; // throwing error
}
}
class test {
public static void main(String[] args) {
Cup<Integer> mycup = new Cup<Integer>(5, 5);
Cup<Integer> momscup = new Cup<Integer>(7, 7);
System.out.println(mycup.getVolume());
}
}
Image of Description
The aim is to have the user select a shape (Square, Triangle or Circle) and then enter a boundary length. Once this information has been input I can then calculate the perimeter and area of their choice.
The problem is I don't want to create new variables for the length and area in each class if I don't have to and would rather have the variables declared and then passed into the classes if I can.
Basically I don't want to do it like this,
class square {
double bLength;
double area;
}
class triangle {
double bLength;
double area;
}
class circle {
double bLength;
double area;
}
Can I declare them outside of the classes and then have the classes use/inherit them or anything?
I must apologise for such a basic question, I am quite new to Java and I can't really think around this one.
The classic solution is to use inheritance:
class Shape {
double bLength;
double area;
Shape(double bLength, double area) {
this.bLength = bLength;
this.area = area;
}
}
class Square extends Shape {
Square(double bLength, double area) {
super(bLength, area);
}
// additional field, methods...
}
// same for the other shapes
You can use inheritance for this problem in following way :
Declare a class called Shape from which all other classes would inherit
public class Shape {
public double length = 0;
public abstract double GetPerimeter();
public abstract double GetArea();
public Shape(double length) {
this.length = length;
}
}
Then have your specialized classes. E.g. :
public class Circle extends Shape {
public Circle(double length) {
super(length);
}
public double GetPerimeter() {
// Implement the perimeter logic here
}
public double GetArea() {
// Implement the area logic here
}
}
Do this for all classes. This way you have the variable in only one class, and all others inherit from it.
EDIT
If you want even further optimization (for instance, you don't want function call overhead), something like perhaps
public class Shape {
public double length = 0;
public double perimeter= 0;
public double area= 0;
public Shape(double length, double perimeter, double area) {
this.length = length;
this.perimeter= perimeter;
this.area = area;
}
}
public class Circle extends Shape {
public Circle(double length) {
super(length, 2 * Math.PI * length, Math.PI * length * length);
}
}
I am trying to create a n-body simulator in Java while also learning OOP.
I want to have a file that contains all physical constants and physics formulas and I want to use these in other classes when calculating forces etc
Should this file be a regular class with all variables static, an interface or an abstract class, or something else? I am quite confused with all the definitions.
In your case I would create a class named Physics or something of that nature. Inside this class you can then accomplish all of the things you want to do by creating static methods and static variables, as JayC667 has pointed out. It should look something like this:
public class Physics {
public static final int GRAVITY_ACCELERATION = 9.58;
public static double formula(double x, double y) { ... }
// etc.
}
Then, to utilize this class from a different one, you simply reference the variables and use the methods like so:
System.out.println("Acceleration of Gravity = " + Physics.GRAVITY_ACCELERATION);
double speed = Physics.formula(23.5, 840);
You use interfaces to force classes (implementing those interfaces) to have defined methods (defined in the interface) you can can ensure basic functionality, while all the classes can be totally different in all other regards.
In an interface, you only define the method signature (return value, name, parameter types). These are purely abstract.
Since Java 8, interfaces can also contain default methods, that may contain code, but can be overridden by the implementing classes.
Best example is the Comparable interface. You can use that for Numbers, Strings, and any other classes that should be comparable (usually to their own class instances aka objects).
Abstract classes are a mixture of regular classes and interfaces. They contain code and member variables, but can also contain abstract methods. When a class extends an abstract base class, they need to implement the abstract methods at some point.
The normal classes do not have any abstract methods.
This is a question Java-developers usually fight over. General rules of thumb are the following:
If you use a static field, always make it final and never try to mutate it.
If you need a mutable field, create a non-static field.
If possible, initialise the field in the constructor and mark it final.
Methods are static only if they access no non-static fields (ie. they do not have a context), there is no need to abstract over them
(for example in a test case) and they are completely functional (this should
be implied by the fact that no static field is mutable). A good example is Math.sqrt(), where the square root operation does not have a context, does not mutate the state of your application and you never want to abstract over it. In all other cases use a non-static method. Some people completely avoid static methods.
Interfaces are most useful when your classes interact with one another. You can specify certain common functionalities available in a group of classes in your application. Then if some of your code requires these functionalities, you can use them without knowing the actual implementation. Say, you handle shapes in a method and want to know the area of a shape. You may have many shapes and you can retrieve the area without knowing the exact type (circle, triangle etc.).
In general, try not to overuse inheritance. Follow the substitution principle: only use inheritance if the superclass could always be substituted by the subclass.
For example: in OOP a square with variable slides is not a rectangle with variable slides, because for rectangles you are allowed to call setSide(20, 30), while for squares you are not (the two sides must match). Note: if you use final fields which are initialized in the constructor, as suggested earlier, this problem is automatically solved and you are free to inherit square from rectangle.
In your case, I would create utility classes with static methods/fields for common functionalities that do not have a context, such as calculating a formula with given input parameters. The actual bodies could be objects with common interface or abstract parent class.
This is some simple example of how you could do it.
Please ignore the aerial resistance part, didn't really think about that, some movements may be funny :-)
import java.util.ArrayList;
/**
* Contains constants and convenience methods
* #author JayC667
*/
class Globals {
static public final float GRAVITY_ACC = -9.81f; // meters per second²
static public float getTotalSpeed(final float pSpeedX, final float pSpeedY) {
return (float) Math.sqrt(Math.pow(pSpeedX, 2) + Math.pow(pSpeedY, 2));
}
static public float getDistanceBetweenObjects(final PhysicalObjectInterface pObj1, final PhysicalObjectInterface pObj2) {
final float distX = pObj2.getPosX() - pObj1.getPosX();
final float distY = pObj2.getPosY() - pObj1.getPosY();
return getTotalSpeed(distX, distY); // coincidentally same as average speed :-)
}
static public String toString(final PhysicalObjectInterface pObject) {
return pObject.getClass().getSimpleName() + "\tX=" + pObject.getPosX() + "\tY=" + pObject.getPosY();
}
}
interface PhysicalObjectInterface {
default boolean collidesWith(final PhysicalObjectInterface pOther) {
final float distance = Globals.getDistanceBetweenObjects(this, pOther);
return distance < getRadius() + pOther.getRadius();
}
float getPosX();
float getPosY();
float getSpeedX();
float getSpeedY();
float getMass();
float getRadius();
float getAerialResistanceCofactor();
void calcNextCycle();
}
/**
* Does most of the simple work
* #author JayC667
*/
abstract class PhysicalObjectABC implements PhysicalObjectInterface {
private float mPosX;
private float mPosY;
private float mSpeedX;
private float mSpeedY;
public PhysicalObjectABC(final float pPosX, final float pPosY, final float pSpeedX, final float pSpeedY) {
mPosX = pPosX;
mPosY = pPosY;
mSpeedX = pSpeedX;
mSpeedY = pSpeedY;
}
#Override public float getPosX() {
return mPosX;
}
#Override public float getPosY() {
return mPosY;
}
#Override public float getSpeedX() {
return mSpeedX;
}
#Override public float getSpeedY() {
return mSpeedY;
}
#Override public abstract float getMass();
#Override public abstract float getAerialResistanceCofactor(); // could also derive this from radius
// getRadius is not repeated here, but still is abstract and has to be defined in the implementing subclass
#Override public void calcNextCycle() {
final float gravForceY = getMass() * Globals.GRAVITY_ACC; // F = m * a
final float aerialResistForceX = -Math.signum(mSpeedX) * (float) (Math.pow(mSpeedX, 2) * getAerialResistanceCofactor());
final float aerialResistForceY = -Math.signum(mSpeedY) * (float) (Math.pow(mSpeedY, 2) * getAerialResistanceCofactor());
final float totalForceX = aerialResistForceX;
final float totalForceY = gravForceY + aerialResistForceY;
final float accX = totalForceX / getMass(); // a= F / m;
final float accY = totalForceY / getMass(); // a= F / m;
mSpeedX += accX;
mSpeedY += accY;
mPosX += mSpeedX;
mPosY += mSpeedY;
}
#Override public String toString() {
return Globals.toString(this);
}
}
class Stone extends PhysicalObjectABC {
public Stone(final float pPosX, final float pPosY) {
super(pPosX, pPosY, 0, 0);
}
#Override public float getRadius() {
return 0.1f;
}
#Override public float getMass() {
return 1;
}
#Override public float getAerialResistanceCofactor() {
return 0.2f;
}
}
class Leaf extends PhysicalObjectABC {
public Leaf(final float pPosX, final float pPosY) {
super(pPosX, pPosY, 0, 0);
}
#Override public float getRadius() {
return 0.1f;
}
#Override public float getMass() {
return 0.003f;
}
#Override public float getAerialResistanceCofactor() {
return 0.95f;
}
}
class StaticObject implements PhysicalObjectInterface {
private final int mPosX;
private final int mPosY;
private final int mRadius;
public StaticObject(final int pPosX, final int pPosY, final int pRadius) {
mPosX = pPosX;
mPosY = pPosY;
mRadius = pRadius;
}
#Override public float getPosX() {
return mPosX;
}
#Override public float getPosY() {
return mPosY;
}
#Override public float getSpeedX() {
return 0;
}
#Override public float getSpeedY() {
return 0;
}
#Override public float getMass() {
return 0;
}
#Override public float getRadius() {
return mRadius;
}
#Override public float getAerialResistanceCofactor() {
return 0;
}
#Override public void calcNextCycle() { /* ignore, does not move */}
#Override public String toString() {
return Globals.toString(this);
}
}
public class PhysicsEngine {
static private ArrayList<PhysicalObjectInterface> sObjects = new ArrayList<>();
public static void main(final String[] args) {
sObjects.add(new Leaf(10, 100));
sObjects.add(new Stone(20, 100));
sObjects.add(new Leaf(30, 100));
sObjects.add(new Stone(40, 100));
sObjects.add(new StaticObject(30, 100, 1)); // lantern
sObjects.add(new StaticObject(40, 100, 5)); // tree
for (int cycle = 0; cycle < 1000; cycle++) {
simulateCycle(cycle);
printData(cycle);
checkCollisions(cycle);
try {
Thread.sleep(1000);
} catch (final InterruptedException e) { /* ignore */}
}
}
private static void simulateCycle(final int pCycle) {
System.out.println("Simulating cycle #" + pCycle);
for (final PhysicalObjectInterface o : sObjects) {
o.calcNextCycle();
}
}
private static void printData(final int pCycle) {
System.out.println("Printing cycle #" + pCycle);
for (final PhysicalObjectInterface o : sObjects) {
System.out.println("\t" + o);
}
}
private static void checkCollisions(final int pCycle) {
System.out.println("Checking for collisions in cycle #" + pCycle);
final ArrayList<PhysicalObjectInterface> destroyedItems = new ArrayList<>();
for (final PhysicalObjectInterface o1 : sObjects) {
for (final PhysicalObjectInterface o2 : sObjects) {
if (o1 == o2) continue; // ignore IDENTICAL, not equal, items
if (o1.collidesWith(o2)) {
System.out.println("CRASH!\n\tObject 1 (" + o1 + ") \ncollides with \n\tObject 2 (" + o2 + ")");
destroyedItems.add(o1);
destroyedItems.add(o2);
}
}
}
sObjects.removeAll(destroyedItems); // can't delete within loop, would invalidate iterators or migh also f*** up loop indices
}
}