Java class without constructor, only static functions - java

I have created the class angle as shown in the codebox below, I want to calculate the difference( called "minus" in the code) of two angles with the following command.
Angle.degrees(135).minus(Angle.degrees(90)).getDegrees()
Unfortunately, I always get zero as result, because the intern values are always overwritten.
import java.lang.Math;
public class Angle {
private static double gradmass = 0;
private static double bogenmass = 0;
public static Angle degrees(double angle) {
Angle angleD = new Angle();
// gradmass = angle;
// bogenmass = Math.toRadians(angle);
angleD.setDegrees(angle);
angleD.setRadians(Math.toRadians(angle));
return angleD;
}
public static Angle radians(double angle) {
Angle angleR = new Angle();
// gradmass = Math.toDegrees(angle);
// bogenmass = angle;
angleR.setDegrees(Math.toDegrees(angle));
angleR.setRadians(angle);
return angleR;
}
public double getDegrees() {
return gradmass;
}
public void setDegrees(double gradM) {
gradmass = gradM;
}
public double getRadians() {
return bogenmass;
}
public void setRadians(double bogenM) {
bogenmass = bogenM;
}
public Angle plus(Angle other) {
Angle temp = new Angle();
temp.setDegrees(this.getDegrees() + other.getDegrees());
temp.setRadians(other.getRadians() + other.getRadians());
return temp;
}
public Angle minus(Angle other) {
Angle temp = new Angle();;
temp.setDegrees(this.getDegrees() - other.getDegrees());
temp.setRadians(this.getRadians() - other.getRadians());
return temp;
}
public Angle neg() {
Angle temp = new Angle();
temp.setDegrees(-this.getDegrees());
temp.setRadians(-this.getRadians());
return temp;
}
public double sin() {
double temp;
temp = Math.sin(this.getDegrees());
return temp;
}
public double cos() {
double temp;
temp = Math.cos(this.getDegrees());
return temp;
}
public boolean similarTo(Angle other){
boolean gleich = false;
if( 0 == (this.getDegrees() - other.getDegrees()) || this.neg().getDegrees() == other.getDegrees()){
gleich = true;
}
return gleich;
}
public String toString(){
return
"GradM " + this.getDegrees() + " BogenM " + this.getRadians();
}
}
I did not make a constructor on purpose! I'm looking for a solution without a constructor or nonstatic methods.

Both your data members are static, meaning there's a single instance of them for the entire class. You should declare them as instance members so that each instance of Angle can have its own values:
public class Angle {
private double gradmass = 0;
private double bogenmass = 0;
// rest of the code...

Don't do this. Your class won't be thread-safe this way. What you want is kind of something like BigDecimal class in java, I guess. You can check the documentation of BigDecimal class of java if you want something like this.
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
But if you want the exact same thing you asked, you can see this (not thread safe and not recommended as well).
class Angle {
static Double angle1 = null;
static Double angle2 = null;
private static void setAngle(double angle) {
if (angle1 == null) angle1 = angle;
else angle2 = angle;
}
static Angle degrees(Double angle) {
setAngle(angle);
return new Angle();
}
static Double getDegrees() {
return angle1;
}
static Angle minus(Angle angle) {
angle1 -= angle2;
return new Angle();
}
}
public class SolutionAngle {
public static void main(String... args) {
System.out.println(Angle.degrees(135).minus(Angle.degrees(90)).getDegrees());
}
}

Related

How do I compare 2 objects with 1 parameter?

I made a java program that compares the distance between 2 objects
I managed to figure out how to solve it when I make a class with 2 parameters and compare these with the formula seen below;
public class RasterServices {
public static double distance (SimpleRasterElement a, SimpleRasterElement b) {
double d;
d = Math.sqrt(((b.x-a.x)*(b.x-a.x)) + ((b.y-a.y)*(b.y-a.y)));
return d;
}
public class SimpleRasterElement {
public int id;
public double x;
public double y;
public double height;
}
public class SimpleRasterElementTest {
public static void main (String[] args)
{
SimpleRasterElement a, b ; // Deklarera variabeln
a = new SimpleRasterElement (); // Skapa en instans (med ’new’),
b = new SimpleRasterElement ();
// Tilldela variablerna i ’a’ värden:
a.id = 1;
a.x = 6.0;
a.y = 8.0;
a.height = 10.5;
// Tilldela variablerna i ’b’ värden:
b.id = 1;
b.x = 9.0;
b.y = 12.0;
b.height = 15.5;
System.out.println (RasterServices.distance(a,b));
}
}
I can then test this via using my test program RasterServices.distance(a,b)
But now I want to make my variables private, use getters and create the distance() method within the RasterElement-class, and now I'm hardstuck.
public class RasterElementTest {
public static void main(String[] args) {
RasterElement re_a = new RasterElement(1, 6.0, 8.0, 10.5);
RasterElement re_b = new RasterElement(1, 9.0, 12.0, 15.5);
double d = re_a.distance(re_b);
System.out.println(d);
}
}
asd
public class RasterElement {
private final int id;
private final double x;
private final double y;
private final double height;
public RasterElement (int id_nr, double x_val, double y_val, double height_val) {
id = id_nr;
x = x_val;
y = y_val;
height = height_val;
}
public int getId () {
return id;
}
public double getX () {
return x;
}
public double getY () {
return y;
}
public double getHeight () {
return height;
}
public double distance (RasterElement a) {
double d;
d = Math.sqrt(((b.getX()-a.getX())*(b.getX()-a.getX())) + ((b.getY()-a.getY())*b.getY()-a.getY()));
return d;
}
}
But here in distance() i'm only allowed ONE parameter, can someone please explain to me how I can compare two elements/objects when I'm only allowed one parameter in the function?
(By using re_a.distance(re_b); in my test-code)
Thanks, sorry for the long post B-)
(how do I get the b-value into the equation in the method distance in the class RasterElement..?)
Change b to this. Also, you can eliminate d and return directly. Like,
public double distance (RasterElement a) {
return Math.sqrt(((this.getX()-a.getX())*(this.getX()-a.getX()))
+ ((this.getY()-a.getY())*this.getY()-a.getY()));
}

How to Implement modifiable activation function in the neuron class in java?

I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {
// properties
private ArrayList<Neuron> input;
private ArrayList<Float> weight;
private float pot, bias, sense, out;
private boolean checked;
// methods
public float fire(){
pot = 0f;
if (input != null) {
for (Neuron n : input){
if (!n.getChecked()){
pot += n.fire()*weight.get(input.indexOf(n));
} else {
pot += n.getOut()*weight.get(input.indexOf(n));
} // end of condition (checked)
} // end of loop (for input)
} // end of condition (input exists)
checked = true;
pot -= bias;
pot += sense;
out = actFunc(pot);
return out;
} // end of fire()
// getting properties
public float getPot(){return pot;}
public boolean getChecked(){return checked;}
public float getOut(){return out;}
// setting properties
public void stimulate(float f){sense = f;}
public void setBias(float b){bias = b;}
public void setChecked(boolean c){checked = c;}
public void setOut(float o){out = o;}
// connection
public void connect(Neuron n, float w){
input.add(n);
weight.add(w);
}
public void deconnect(Neuron n){
weight.remove(input.indexOf(n));
input.remove(n);
}
// activation function
private float actFunc(float x){
if (x < 0) {
return 0f;
} else {
return 1f;
}
}
// constructor
public Neuron(Neuron[] ns, float[] ws, float b, float o){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
} else {
input = null;
weight = null;
}
bias = b;
out = o;
}
public Neuron(Neuron[] ns){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
} else {
input = null;
weight = null;
}
bias = (float)Math.random();
out = (float)Math.random();
}
}
First, define interface of any activation function:
public interface ActivationFunction {
float get(float f);
}
Then write some implementations:
public class StepFunction implements ActivationFunction {
#Override
public float get() {return (x < 0) ? 0f : 1f;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get() {return StrictMath.tanh(h);}
}
Finally, set some implementation to your Neuron:
public class Neuron {
private final ActivationFunction actFunc;
// other fields...
public Neuron(ActivationFunction actFunc) {
this.actFunc = actFunc;
}
public float fire(){
// ...
out = actFunc.get(pot);
return out;
}
}
as following:
Neuron n = new Neuron(new SigmoidFunction());
Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
float get(float f);
float firstDerivative(float x);
}
So the implemenations will look like:
public class StepFunction implements ActivationFunction {
#Override
public float get(float x) {return (x < 0) ? 0f : 1f;}
#Override
public float firstDerivative(float x) {return 1;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get(float x) {return StrictMath.tanh(x);}
// derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
#Override
public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}
Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.

Java adding to arraylist overrides other values

So I have this piece of code:
private ArrayList<Triangle3D> combine(ArrayList<Triangle2D> leftTriangles, ArrayList<Triangle2D> rightTriangles) {
ArrayList<Triangle3D> returnTriangles = new ArrayList<Triangle3D>();
for (Triangle2D eL : leftTriangles){
Triangle2D eR = eL.getOtherTriangle(rightTriangles);
if(eR != null){
ArrayList<Point3d> corners = new ArrayList<Point3d>(3);
for(Tuple<Integer, Integer> cornerL : eL.getCorners()){
Tuple<Integer, Integer> cornerR = eR.getCorrespondingCorner(cornerL);
if(cornerL != cornerR){
corners.add(addDistances(cornerL, cornerR));
}
}
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
}
}
return returnTriangles;
}
But for some reason whenever i excecute the line:
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
The previous "corners" values of the Triangle3D elements that are already in the list get overriden by the newle added ones. Which I think is weird because I clearly make a new Arraylist on this line:
ArrayList<Point3d> corners = new ArrayList<Point3d>(3);
I defined the Tuple class myself as following:
package vision.polyhedradetection;
public class Tuple<X, Y> {
private final X x;
private final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
public X getX() { return x; }
public Y getY() { return y; }
public Tuple<X, Y> copy(){
return new Tuple<X,Y>(this.x, this.y);
}
#Override
public String toString() {
return "(" + x + "," + y + ")";
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Tuple)){
return false;
}
Tuple<Integer, Integer> other_ = (Tuple<Integer, Integer>) other;
return other_.x == (this.x) && other_.y == (this.y);
}
}
EDIT:
I found the root of the problem. But still don't know how to fix it. It's in my Triangle3D class. This is my class:
package vision.polyhedradetection;
import javax.vecmath.Point3d;
import java.util.List;
public class Triangle3D {
private static Point3d corner1 = new Point3d();
private static Point3d corner2 = new Point3d();
private static Point3d corner3 = new Point3d();
private int color;
public Triangle3D(Point3d corner1, Point3d corner2, Point3d corner3, int color) {
this.corner1 = corner1;
this.corner2 = corner2;
this.corner3 = corner3;
this.color = color;
}
public Triangle3D(List<Point3d> corners, int color) {
this.corner1 = corners.get(0);
this.corner2 = corners.get(1);
this.corner3 = corners.get(2);
this.color = color;
}
private static Point3d centroid;
public Triangle3D(Point3d centroid, int color) {
this.centroid = centroid;
this.color = color;
}
public Point3d[] getCorners() {
Point3d[] Corners = {corner1, corner2, corner3};
return Corners;
}
public int getColor() {
return this.color;
}
public Point3d getCentroid() {
if (this.centroid != null) return this.centroid;
else {
Double x = (double) Math.round((corner1.x + corner2.x + corner3.x) / 3);
Double y = (double) Math.round((corner1.y + corner2.y + corner3.y) / 3);
Double z = (double) Math.round((corner1.z + corner2.z + corner3.z) / 3);
this.centroid = new Point3d(x, y, z);
return this.centroid;
}
}
}
The problem lies in this code in my combine function:
returnTriangles.add(new Triangle3D(corners, eL.getColor()));
For some reason when I create this new Triangle3D my corner1, corner2, corner3 in the "new" creating triangle are already set (thus they are pointing to my already existing corners). How do I get rid of this dependency? I don't get it since i make new corners when I create that class.
Can you provide me with example data where I can see the value being overridden?
ArrayList.add add an element, it does not replace an element.
Your corners is within the for loop scope, so it shouldn't save any previous data.
I do not think you have debugged it properly and mistakenly think that it replaces the previous value. I would gladly help you, but I need the same data as the data that you have used.

How to use methods which are not in interface with interface i = new class();

I am only able to access methods/vars of m1/m2 which are in the interface Measurable how do i access other methods and vars?
How is it possible to use the getLength() AND getBreadth()/getRadius() method of m1/m2 object in the getArea() method? Thanks in Advance!
public class Main {
public static void main(String[] args) {
Circle c = new Circle(10);
Rectangle r = new Rectangle(10,5);
addArea(c, r);
Measurable Rec = new Rectangle(10, 5);
Measurable Cir = new Circle(10);
addArea(Rec, Cir);
}
public static void addArea(Measurable m1, Measurable m2){
String m1s = null,m2s = null;
if(m1 instanceof Rectangle){
m1s="Rectangle";
}
else if(m1 instanceof Circle){
m1s="Circle";
}
if(m2 instanceof Circle){
m2s="Circle";
}
else if(m2 instanceof Rectangle){
m2s="Rectangle";
}
System.out.println("Area of "+m1s+" and "+m2s+" is "+(m1.getArea()+m2.getArea())+"\n");
}
}
interface Measurable{
double PI = 3.14;
public double getPerimeter();
public double getArea();
}
class Rectangle implements Measurable{
public double breadth, length;
public Rectangle(int breadth, int length){
this.breadth = breadth;
this.length = length;
}
#Override
public double getPerimeter() {
return 2*(breadth+length);
}
#Override
public double getArea() {
return length*breadth;
}
public double getLength(){
return length;
}
public double getBreadth(){
return breadth;
}
}
class Circle implements Measurable{
public double radius;
public Circle(int radius){
this.radius = radius;
}
#Override
public double getPerimeter() {
return 2*PI*radius;
}
#Override
public double getArea() {
return PI*radius*radius;
}
public double getRadius(){
return radius;
}
}
You should cast your objects, do that in your if blocs and assign the value to a String object. The reference of the interface can not make a call to a method written in one class that implements it.
Solution
E.g for getLength() and m1
String m1Length = null;
if(m1 instanceof Rectangle){
m1s="Rectangle";
m1Length = ((Rectangle)m1).getLength());
}
else if(m1 instanceof Circle){
m1s="Circle";
m1Length = ((Circle)m1).getLength());
}
Apply this logic to the rest of the code and you'll be fine.

Entire array being reset when trying to set a single position

I have really straight forward code, I am hoping that my issue is that I have just been looking at it too long. I am testing some calculations to make sure I am doing it right before I throw in a huge list. All I want to do is create a new objects through a for loop and toss them in my constructed array.
Contents of public static void main(String args[]) in my Main class:
PositionHolder[] positions = new PositionHolder[8];
PositionHolder currPosition;
int currPos = 0;
for(int i = 0; i <= 7; i++){
/* For Random Points */
currPosition = new PositionHolder(i);
System.out.println("Resetting " + i);
positions[i] = currPosition;
//positions[i].setxPos(100 * Math.random()); // these get set in the
//positions[i].setyPos(100 * Math.random()); // PositionHolder constructor
for(int k = i; k >= 0; k--){
System.out.println(k + ": " + positions[k].getxPos() + ", " + positions[k].getyPos());
}
}
Just for clarification, my PositionHolder class is as follows:
public class PositionHolder {
private static double xPos;
private static double yPos;
private static int point;
private static boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
PositionHolder.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
PositionHolder.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
PositionHolder.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
PositionHolder.visited = visited;
}
}
The problem is that for some reason each time through the for loop override the previous PositionHolders I have put in my array. As a quick example, here is the first few lines of my system output from the System.println towards the end of the for loop:
Resetting 0
0: 60.697435147416186, -96.35236848097432
Resetting 1
1: 57.98340997157546, -52.56948459757237
0: 57.98340997157546, -52.56948459757237
Resetting 2
2: 45.75236962694197, -32.03840605394901
1: 45.75236962694197, -32.03840605394901
0: 45.75236962694197, -32.03840605394901
So where I want 0 to stay at 60.69743.... and 1 to stay at 57.98340.... they are all getting set to the same (most resent) value. I wish I could say it is more complex than that, but that is it. What is going on?
--- The Answer, given below by Logan Murphy, is correct ---
As a note, not only should you take a break from time to time to avoid silly mistakes from code you have looked at too much, but you REALLY shouldn't rely on eclipses "fix" solutions to make good code :P
Because you set your variables to be static (shared between instances of the class). They need to be non-static like so
public class PositionHolder {
private double xPos;
private double yPos;
private int point;
private boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
this.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
this.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
}
This way each instance of the class PositionHolder has its own variables (instance variables are globally declared variables that are non-static)

Categories

Resources