How do I compare 2 objects with 1 parameter? - java

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()));
}

Related

Java class without constructor, only static functions

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());
}
}

Java - Static Variables

If I wanna create a static variable inside this class, which should save the total amount of all accounts. Is this right the way I did it?
Just put a code inside the constructor and good is.
Should anyway only be inside a constructor, right?
How can I print static variables so I am able to check it?
public class Account {
private static double totalBalance = 0;
private final double INTEREST_RATE = 0.015;
private int acctNumber;
private double balance;
private String name;
public Account(String name, int acctNumber, double initialBalance) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = initialBalance;
this.totalBalance += this.balance;
}
public Account(String name, int acctNumber) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = 0.0;
this.totalBalance += this.balance;
}
To much code for simple question. The main thing is keyword static when declaring the field in the class. Always remember that these fields are shared among all instances of the class. In other words, when some instance change the value of the static field it is reflected in the all other instances of that class. Here the simple code is better than the words:
class A {
public static int x;
}
public class Helper {
public static void main(String[] args) {
A someA = new A();
A.x = 0;
A someOtherA = new A();
A.x = 5;
//uncomment next line and see what happens
//someA.x = -55;
System.out.println("x in someA = " + someA.x);
System.out.println("x in someOtherA = " + someOtherA.x);
System.out.println("x in all instances of A = " + A.x);
}
}
EDIT:
About the question can I put the static variable inside the constructor, try this:
class B{
private static int x;
public B(int x){
B.x = x;
}
public int getX() {
return x;
}
}
public class Helper {
public static void main(String[] args) {
B bOne = new B(44);
System.out.println(bOne.getX());
B bTwo = new B(88);
System.out.println(bTwo.getX());
System.out.println(bOne.getX());
}
}
EDIT two
Here is the sample code regarding your questions in the comments:
class Acc {
public static int noOfAccounts;
public static double totalBalance;
public Acc(double balance) {
//increase the number of accounts
Acc.noOfAccounts++;
//add the balance to totalBalance
Acc.totalBalance += balance;
}
}
public class Helper {
//test
public static void main(String[] args) {
Acc aOne = new Acc(15.4);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
Acc aTwo = new Acc(100.0);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
}
}
Solution summarized:
static variable:
private static double totalBalance;
constructor 1:
totalBalance += this.balance;
others:
totalBalance += amount;
totalBalance -= (amount + fee);
totalBalance += (this.balance * INTEREST_FEE);

How to make a singleton reinitialize variables?

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;
}
}

How to debug "illegal start of expression" in Java?

In Jcreator, there are 12 errors here, I don't know how to fix it. It says "illegal start of expr....".
If I change something, suddenly, 50 errors more.
public class Practica_figura {
Class Figura() {
private float base;
private float altura;
private float radio;
}
public void asignar(float ba, float al, float ra) {
base = ba;
altura = al;
radio = ra;
}
class Cuadrado extends Figura()
{
private float base;
private float altura;
public void calcular_area(float b, float a) {
float res = base * altura;
}
public void calcular_perimetro(float a) {
float resp = 4 * a;
}
public void rareac() {
return area;
}
public void rperic() {
return perimetro;
}
}
class Triangulo extends Figura()
{
private float base;
private float altura;
private float la;
private float lb;
private float lc;
public void asignar(float a, float b, float c) {
la = a;
lb = b;
lc = c;
}
public void calcular_area(float b, float a) {
float res = (base * altura) / 2;
}
public void calcular_perimetro(float a) {
float resp = 4 * a;
}
public void rareat() {
return area;
}
public void rperit() {
return perimetro;
}
}
public static void main(String[] args) {
// TODO code application logic here
float base = 0, altura = 0, radio = 0;
JOptionPane.showMessageDialog(null, "Programa para calcular área y perímetro");
}
}
To have a correct class definition change
public class Practica_figura { Class Figura(){
to
public class Figura{
I don't really understand what you were trying to do, if what you wanted was a constructor then you would have to add:
public Figura(){
}
First, the class is not quite defined properly.
public class Practica_figura
{
private float base;
private float altura;
private float radio;
public Practica_figura()
{
}
public void asignar(float ba, float al, float ra)
{
base = ba;
altura = al;
radio = ra;
}
//edits assuming you want inner classes
class Figura
{
private float base, altura, radio;
// you will need getters/setters for the variables
}
class Cuadrado extends Figura
{
// insert class logic here
}
class Triangulo extends Figura
{
// insert class logic here
}
}
Second, you are shadowing variables in your child classes, and this approach may make things confusing.

aggregation in Java and methods in main method

I have such code which works well, but I wonder why method area is not possible to put in the main method
public class Circle {
Operation op;
double pi = 3.14;
double area(int radius) {
op = new Operation();
int rsquare = op.square(radius);
return rsquare * pi;
}
public static void main(String arg[]) {
Circle c = new Circle();
double s = c.area(5);
System.out.println(s);
}
class Operation {
int square(int n) {
return n * n;
}
}
}
Example which doesn't work:
public static void main(String arg[]) {
double area ( int radius){
op = new Operation();
int rsquare = op.square(radius);
return rsquare * pi;
}
The only way to nest method implementation code inside Java methods is with anonymous classes. In your case this would look like this (code has to be nested inside a class of sorts):
public static interface Circle {
double area(int radius);
}
public static interface Operation {
int square(int n);
}
public static void main(String arg[]) {
Circle c = new Circle() {
Operation op;
double pi = 3.14;
public double area(int radius) {
op = new Operation() {
public int square(int n) {
return n * n;
}
};
int rsquare = op.square(radius);
return rsquare * pi;
}
};
double s = c.area(5);
System.out.println(s);
}
Take
double area(){...}
Outside of the main method
Java doesn't support nested methods, even if it did, there would be no point to put a nonstatic method in a static method
The closest thing would be nested classes that contain methods, declared in the method

Categories

Resources