My singleton class:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}
Other class that changes singleton values and tries to reinitialize. My question is if I call changeXandY a few times then want to call resetXandY how do I make it reset back to the original x and y?
public class GameWorld {
private List<GameObject> objects;
public void initialize() {
objects = new ArrayList<GameObject>();
objects.add(XandY.getXandY());
...add other objects that are not singletons
}
public void changeXandY {
for (int i=0; i<gameObject.size(); i++) {
if (gameObject.get(i) instanceof XandY)
((XandY)gameObject.get(i)).updateXandY();
}
public void resetXandY {
initialize();
}
}
For this use case, you could simply store them as default values. Such as
private double x, y;
private static XandY xy;
private static final double default_x = 210.0;
private static final double default_y = 100.0;
That way when you reset, just:
public void resetXandY {
this.x = default_x;
this.y = default_y;
}
That being said, you may want to change your default constructor to look the same way.
If you can make the XandY reference protected, you can use a static initializer in an anonymous subclass:
// I need to reset the singleton!
new XandY(){
{ xy = null; }
};
But really, if you need to be able to (re)initialize the singleton, you should put a method to that effect into its signature. Obscure solutions are, at best, still obscure...
Create a resetXandY() method to set default value:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
//reset x=0 and y=0
public void resetXandY() {
x = 0;
y = 0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}
Related
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()));
}
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());
}
}
I am working on a java project which contains 3 classes and an object array in one of the classes. This project is ultimately supposed to move 4 entity objects around on a board by using the coordinates of the entity objects. These entity objects are stored in an array in the world class. My problem is with the array initialization in the world class. I am not sure how to set each element of the array equal to an object from the entity class and then access that object's coordinates to move it around on the board. The coordinates for the entity objects are initially set at 20x30 in a default constructor. Here is my code:
public class entity {
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public entity(){
xcoordinate = 20;
ycoordinate = 30;
}
private entity(int newxcoor, int newycoor, String newname, char newsymbol){
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor(){
return xcoordinate;
}
public int getYCoor(){
return ycoordinate;
}
}
public class world {
private entity[] ObArray = new entity[4];
public world(){
world test = new world();
}
public void draw(){
for (int i = 0; i < 4; i++)
{
//int x = ObArray[i].getXLoc();
//int y = ObArray[i].getYLoc();
}
}
}
public class mainclass {
public static void main(String[] args){
world worldob = new world();
//entity a = new entity();
//entity b = new entity();
//entity c = new entity();
//entity d = new entity();
worldob.draw();
}
}
My draw function and main function are not finished. After the array is initialized I will be able to finish the draw method using the entity get functions.
Thanks for your help.
That is one way of doing it. You can also define all of your entities inline like this:
private entity[] ObArray = {
new entity(0,0,"Entity1",'a'),
new entity(10,10,"Entity2",'b'),
new entity(20,20,"Entity3",'c'),
new entity(30,30,"Entity4",'d')
};
A better way may be to do an ArrayList instead of an array:
private List<entity> ObArray = new ArrayList<>();
ObArray.add(new entity(0,0,"Entity1",'a');
ObArray.add(new entity(10,10,"Entity2",'b');
ObArray.add(new entity(20,20,"Entity3",'c');
ObArray.add(new entity(30,30,"Entity4",'d');
To access each element you just need to get the element from the array and either get or set the properties you need:
ObArray[0].getXCoor();
ObArray[0].setXCoor(5);
Your problem is only creating new object of world inside world's constructor which throws stack overflow error, otherwise it is fine:
public world(){ world test = new world(); //REMOVE THIS LINE
}
You simply need to initialise the array. This can be done in the world constructor.
public world()
{
for (int i = 0; i < 4; i++)
{
ObArray[i] = new entity();
}
}
Then you can access the objects in your draw method, as you've shown:
public void draw()
{
for (int i = 0; i < 4; i++)
{
int x = ObArray[i].getXCoor();
int y = ObArray[i].getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
// Manipulate items in the array
// ObArray[i].setXCoor(10);
}
}
A more complete example, with the move functions added, and the class names capitalised:
public class Entity
{
private int xcoordinate;
private int ycoordinate;
private String name;
private char symbol;
public Entity()
{
xcoordinate = 20;
ycoordinate = 30;
}
private Entity(int newxcoor, int newycoor, String newname, char newsymbol)
{
xcoordinate = newxcoor;
ycoordinate = newycoor;
name = newname;
symbol = newsymbol;
}
public int getXCoor()
{
return xcoordinate;
}
public void setXCoor(int xcoordinate)
{
this.xcoordinate = xcoordinate;
}
public int getYCoor()
{
return ycoordinate;
}
public void setYcoor(int ycoordinate)
{
this.ycoordinate = ycoordinate;
}
public static void main(String[] args)
{
World worldob = new World();
worldob.draw();
worldob.move(0, 15, 30);
worldob.move(1, 45, 0);
worldob.move(2, 23, 27);
worldob.move(3, 72, 80);
worldob.draw();
}
}
class World
{
private final Entity[] ObArray;
public World()
{
this.ObArray = new Entity[4];
for (int i = 0; i < ObArray.length; i++)
{
ObArray[i] = new Entity();
}
}
public void move(int index, int xCoor, int yCoor)
{
if (index >= 0 && index < ObArray.length)
{
Entity e = ObArray[index];
e.setXCoor(xCoor);
e.setYcoor(yCoor);
}
}
public void draw()
{
for (Entity e : ObArray)
{
int x = e.getXCoor();
int y = e.getYCoor();
System.out.println("x" + x);
System.out.println("y" + y);
}
}
}
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)
I am wondering why i have to deal with two types of arguments;that of a constructor and that of a method.For instance i have this simple class that adds two numbers
class Calc{
private int x = 6;
private int y;
private char z = 'z';
public int getx(){
return x;
}
public char selfrecur(){
return this.z;
}
public int add(int one,int two){
return one + two;
}
public static void main(String[] args) {
Calc gx = new Calc();
System.out.println(gx.x);
System.out.println(gx.add(44,3));
System.out.println(gx.selfrecur());
}
}
That works,and wow,wasn't that great.Now,i have this idea of having the constructor provide the arguments and the function's work will be to do the heavy computations.For instance in my class Kalc
class Kalc{
//** This example won't work **
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return newObject.x + newObject.y + newObject.z;
//Gets the values of a new object and add them up
}
public int multiply(){
return newObject.x * newObject.y * newObject.z;
//Gets the values of a new object and multiply them
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add());
System.out.println(k.multiply());
}
}
I have been looking here http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html for clues but so far nothing.Is this even possible?.
Edit
class Kalc{
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3){
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return this.x + this.y + this.z;
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add);
}
}
Error
C:\ja>javac Kalc.java
Kalc.java:17: error: cannot find symbol
System.out.println(k.add);
^
symbol: variable add
location: variable k of type Kalc
1 error
C:\ja>
Use this key word:
public int add(){
return this.x + this.y + this.z;
}
You can use this key word inside non-static methods too.
About your edit:
add is a function (and not a member) of class Kalc so you can call it as a function only:
System.out.println(k.add());
You can do the below
class Kalc{
private int x;
private int y;
private int z;
public Kalc(int v1,int v2,int v3)
{
this.x = v1;
this.y = v2;
this.z = v3;
}
public int add(){
return x+y+z;
}
public int multiply(){
return x*y*z;
}
public static void main(String[] args) {
Kalc k = new Kalc(4,5,6);
System.out.println(k.add());
System.out.println(k.multiply());
}
}
What is newObject?
You have instantiated an object with prescribed values. If you want to add them with an instance method, try this
return this.x + this.y + this.z;
I think you need to print :
System.out.println(k.add());
Instead of :
System.out.println(k.add);
as in the second case the compiler show k.add as add variable
but in the first case add() the compiler show add() as a function which you define in Kalc Class