Questions regarding alias in Java - java

public class Vector {
private int x, y, z;
public Vector(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void add(Vector v) {
x += v.x;
y += v.y;
z += v.z;
}
public void silly(int x, int y, int z) {
this.x = ++x;
this.y = y + 1;
this.z += z;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
#Override
public String toString() {
return "Vector, <x = " + x + ", y = " + y + ", z = " + z + ">";
}
public static void main(String[] args) {
Vector a = new Vector(1, 0, 0);
Vector b = new Vector(0, 1, 0);
Vector c = a;
int x = 1;
int y = 2;
int z = 3;
a.add(b);
b.add(b);
c.add(c);
c.silly(x, y, z);
System.out.println("a: " + a);
System.out.println("b: " + b);
System.out.println("c: " + c);
System.out.println("x: " + x + "\ty: " + y + "\tz: " + z);
}
}
I have obviously been unclear in my question, sorry about that. I got this as practice from my teacher and I am supposed to explain the output of the last 4 lines in the code. I have no idea why the output looks as it does. I'm not very good at alias and so on. Someone might be able to give me an explanation? Thanks.

Vector c = a;
means that you create reference which is linked to reference a and its object. You don't call a constructor there. You don't create any object there. Just new reference

The only question I can see is 'What is the relation between Vectors a and c?' So I'll answer that.
When you use the 'new' keyword you are creating a new object which is stored in the heap. So 'a' and 'b' are two separate objects when they have been instantiated. When you say:
Vector c = a;
You are not creating a new object in the heap, merely making a new reference to the same object. So now both 'a' and 'c' are referencing the same thing. If you change a, c will change, and vice versa.
When:
c.add(c);
Is called then the ints in c are simply being added to themselves.

Related

How to solve a linear system in java

public Point intersects(Line line) {
Line holder = new Line(slope, yintercept);
double x;
double y;
if (Math.abs(slope - line.slope) < 0.0000000001) {
return null;
// because can't be parallel and if they don't intercept it has to return null
} else {
//no clue what to do here
y = (holder.slope*x+yintercept);
}
Point interception = new Point(x, y);
return interception;
I don't know how to figure what x would be equal to thanks for help in advance
Try this version with f(x) = m * x + c ...
class LineIntersectException extends Exception
{
LineIntersectException(String message)
{
super(message);
}
}
public static Point intersect(Line line1, Line line2)
{
if(line1.m == line2.m)
{
throw new LineIntersectException("The two lines don't intersect");
}
double x = (line1.c - line2.c) / (line1.m - line2.m);
double y = this.m * x + this.b;
return new Point(x, y);
}
When you have L1 = ax + c and L2 = bx + d (a and b are the slopes and c and d are intercepts).
At the point where lines intersects L1 = L2 so ax + c = bx + d, then
ax - bx = d - c so x = (d-c)/(a-b).
If we want to find y then use calculated above x and we have:
y = a * ((d-c)/(a-b) + c,
hence the point of intersection is:
P((d-c)/(a-b), (ad-bc)/(a-b))

Use variables as parameters

I have a class
public class Coordinates {
public int x,y,z;
public Coordinates (x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
}
In another class' method I want to get access on the coordinates, but I have to do the same long code for each coordinate x,y and z. Is there a way to use variables for the parameters such as :
Coordinates coords0 = new Coordinates(1, 2, 3);
Coordinates coords1 = new Coordinates(4, 1, 3);
Coordinates coords2 = new Coordinates(5, 1, 3);
Coordinates coords3 = new Coordinates(1, 1, 3);
Coordinates coords4 = new Coordinates(1, 2, 0);
Set<Coordinates> set = new HashSet<Coordinates>();
set.add(coords0);
set.add(coords1);
set.add(coords2);
set.add(coords3);
set.add(coords4);
int sum = 0;
for (int i = 0; i < 3; i++) {
String param = "";
if(i == 0) param = "x";
if(i == 1) param = "y";
if(i == 2) param = "z";
Iterator<Coordinates> it = set.iterator();
while(it.hasNext()) {
Coordinates currentCoords = it.next();
sum += currentCoords.param;
}
}
This does not work obviously, but is there a way to achieve something similar to this ?
As far as I understand, the problem is that you must apply the same code to a collection of coordinates, and this same code must be done for all the x of the coordinates, then to all the y of the coordinates, then for all the z of the coordinates.
So you probably need a method looking like this:
private void complexCode(Collection<Coordinates> collection, ToIntFunction<Coordinates> axisAccessor) {
// ...
for (Coordinates c : collection) {
int axis = axisAccessor.applyAsInt(c);
//...
}
// ...
}
You would then call your function three times using
complexCode(collection, coordinates -> coordinates.x);
complexCode(collection, coordinates -> coordinates.y);
complexCode(collection, coordinates -> coordinates.z);
Your current attempt is pretty close, only you don't need a param variable, println (and based on a comment, eliminate the i value). Like,
Coordinates coords = new Coordinates(1, 2, 3);
System.out.println("Coordinate x is " + coords.x);
System.out.println("Coordinate y is " + coords.y);
System.out.println("Coordinate z is " + coords.z);
or format it a little differently, and override toString() in Coordinates. Oh, and fix the constructor.
public class Coordinates {
public int x, y, z;
public Coordinates(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
#Override
public String toString() {
return String.format("x=%d, y=%d, z=%d", x, y, z);
}
}
Then you could print it like
Coordinates coords = new Coordinates(1, 2, 3);
System.out.println("Coordinate " + coords);
What you want is a getter method. It is a good idea to create setter methods as well. Heres what they look like for x. You'll need to make similar methods for y and z.
public int getX(){
return x;
}
public void setX(int newX){
x = newX;
}
you create these in your Coordinates class then from your other class you can do
if(i == 0) param = coords.getX();
You can use reflection like this:
int paramInt = Coordinates.class.getField(param).getInt(coords);
System.out.println("Coordinate "+param+" is "+paramInt);
Don't.

How do I print original point coordinates if I translate a point outside of a certain square?

I'm trying to print the coordinates of a translated point. If the point is translated outside of the 10, -10 range on both the x and y axes, then the original point should be returned and not the translated one. So, for p1 (5,4), if I were to translate it by (7,8), it should return (5,4). I'm having trouble figuring out how exactly to tell Java to print the original point in this case. Do I need to include a Boolean of some sort? Here's what I have so far. (The code is written in German, but "verschiebe" means translate.) Any help would be greatly appreciated! Thanks y'all in advance :)
public class Punkt2 {
private int x;
private int y;
public void setX (int i) {
x = i;
}
public void setY (int i) {
y = i;
}
public void verschiebe(int deltaX, int deltaY){
x = x + deltaX;
y = y + deltaY;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public static void main (String[] args){
Punkt p1 = new Punkt();
p1.setX(5); p1.setY(4);
Punkt p2 = new Punkt();
p2.setX(2);p2.setY(1);
p1.verschiebe(7,8);
if (p1.getX() > 10 || p1.getY() > 10 || p1.getX() < -10 || p1.getY() < -10){
System.out.println(new Punkt());
}
else {
System.out.println(p1.getX() + "," + p1.getY());
}
p2.verschiebe(3, 2);
if (p2.getX() > 10 || p2.getY() > 10 || p2.getX() < -10 || p2.getY() < -10){
System.out.println(new Punkt());
}
else {
System.out.println(p2.getX() + "," + p2.getY());
}
}
}
If you mean that you don't want the point's x or y value to be over 10 or below -10, you can just simply not change the values in the verschiebe method.
Like this:
public void verschiebe(int deltaX, int deltaY){
if(x + deltaX <= 10 && x + deltaX >= -10){
x = x + deltaX;
}
if(y + deltaY <= 10 && y + deltaY >= -10){
y = y + deltaY;
}
}
Then the point's x and y value will stay the same if they are about to get greater than 10 or lesser than -10. So now in the main class you can just print the point you want to and your verschiebe method will take care that your x and y will always be between -10 and 10.
The usual way of doing this would be to check the bounds inside of the translate() method.
For example:
private boolean outOfBounds(point, bounds) {
return (abs(point) > bounds);
}
public void translate(int deltaX, int deltaY) {
int newX = x + deltaX;
int newY = y + deltaY;
if(outOfBounds(newX, 10) || outOfBounds(newY, 10)) {
return;
}
x = newX;
y = newY;
}
Have a Punkt object be responsible for translating points by returning a "translated" point. It can return self when the translation results in point that is out of bounds.
class Punkt {
private int x;
private int y;
public Punkt(int x, int y) {
this.x = x;
this.y = y;
}
public Punkt verschiebe(int dX, int dY) {
int newX = x+dX;
int newY = y+dY;
if (abs(newX) > 10 || abs(newY) > 10) {
return this;
}
return new Punkt(newX, newY);
}
public void print() {
System.out.println(x + "," + y);
}
}
Would also advise that you have Punk print itself, so your clients can look as:
public static void main (String[] args){
Punkt p1 = new Punkt(5, 4);
Punkt p2 = new Punkt(2, 1);
p1.verschiebe(7,8).print();
p2.verschiebe(3,2).print();
}
Better still, if the client actually needs to print translated points the above code can be further improved to:
public static void main (String[] args){
Punkt p1 = new Punkt(5, 4);
Punkt p2 = new Punkt(2, 1);
p1.printTranslated(7,8);
p2.printTranslated(3,2);
}
It's not hard to have Punkt comply to client's needs.

How do I introduce encapsulation in the following Java program? [closed]

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 6 years ago.
Improve this question
I have created the following Java program. Its basic functionality is to perform addition, subtraction, multiplication, division and modular division on two numbers.
I have implemented the concept of object-oriented programming, but it is missing encapsulation.
How do I introduce encapsulation in it?
My code is:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author piyali
*/
public class Calculator {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int x, y;
x = 13;
y = 5;
calculation add = new calculation();
calculation sub = new calculation();
calculation mul = new calculation();
calculation div = new calculation();
calculation mod = new calculation();
int addResult = add.addition(x, y);
int subResult = sub.subtraction(x, y);
int mulResult = mul.multiplication(x, y);
int divResult = mul.division(x, y);
int modResult = mod.modularDivision(x, y);
System.out.println("The addition of the numbers is " +addResult);
System.out.println("The subtraction of the two numbers is " +subResult);
System.out.println("The multiplication of the two numbers is " + mulResult);
System.out.println("The division of the two numbers is " +divResult);
System.out.println("The modular division of the two numbers is " + modResult);
}
}
class calculation {
int addition(int x, int y){
int z;
z = x + y;
return(z);
}
int subtraction(int x, int y){
int z;
z = x - y;
return(z);
}
int multiplication(int x, int y){
int z;
z = x * y;
return(z);
}
int division(int x, int y){
int z;
z = x / y;
return(z);
}
int modularDivision(int x, int y){
int z;
z = x % y;
return(z);
}
}
Well if you want true OOP and encapsulation, then create interface Calculation which has a method int calculate().
public interface Calculation {
int calculate();
}
Now create classes which implements this interface such as Addition or Subtraction etc.
public class Addition implements Calculation {
private final int x;
private final int y;
public Addition(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public int calculate(){
return x + y;
}
}
Main method
public static void main(String[] args) {
int x, y;
x = 13;
y = 5;
Calculation add = new Addition(x, y);
System.out.println(add.calculate());
}
Advantages of such design is that if you will want to add any extra mathematical operations such as root, percentage or even derivation, you will not need to modify any implementation of class. Just write extra class which implements Calculation.
I don't think there's much to encapsulate here. This looks like it wants to be a basic math library, and since it has no data members, or helper functions, you can't do a whole lot here to encapsulate.
Since creating an instance of this class is a bit silly (see the Java Math library for example), make the methods static, and make the constructor private.
I guess not a form of encapsulation, but some design tips: You should make variables you aren't modifying final. You should also remove all unnecessary variables if you aren't using them. They aren't doing anything for readability, and they're just using extra blocks of memory (unless the JVM optimizes them out).
Improved code:
class calculation {
private calculation() {
throw new RuntimeException("Don't instantiate a math library!");
}
public static int addition(final int x, final int y){
return x + y;
}
public static int subtraction(final int x, final int y){
return x - y;
}
public static int multiplication(final int x, final int y){
return x * y;
}
public static int division(final int x, final int y){
return x / y;
}
public static int modularDivision(final int x, final int y){
return x % y;
}
}
By doing this, now you can call your calculation library with something like this:
int additionResult = calculation.addition(5, 5);
System.out.println(additionResult);
Use the concept of getter and setter.
class Calculator{
private int x, y, z;
void setValue(int a, int b){
x=a;
y=b;
}
int getValue(){
return z;
}
void addition(){
z=x+y;
}
void subtraction(){
z=x-y;
}
void multiplication(){
z=x*y;
}
void division(){
z=x/y;
}
void modDivision(){
z=x%y;
}
}
public class CalculatorTestDrive {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1, num2, result;
num1=13;
num2=5;
Calculator add = new Calculator();
Calculator sub = new Calculator();
Calculator mul = new Calculator();
Calculator div = new Calculator();
Calculator mod = new Calculator();
add.setValue(num1, num2);
add.addition();
result = add.getValue();
System.out.println("The addition of " + num1 + " and " + num2 + " is " +result);
sub.setValue(num1, num2);
sub.subtraction();
result = sub.getValue();
System.out.println("The subtraction of " + num1 + " and " + num2 + " is " +result);
mul.setValue(num1, num2);
mul.multiplication();
result = mul.getValue();
System.out.println("The multiplication of " + num1 + " and " + num2 + " is " +result);
div.setValue(num1, num2);
div.division();
result = div.getValue();
System.out.println("The division of " + num1 + " and " + num2 + " is " +result);
mod.setValue(num1, num2);
mod.modDivision();
result = mod.getValue();
System.out.println("The modular division of " + num1 + " and " + num2 + " is " +result);
}
}

Multi-Level inheritance not working

I'm working on a lab for school and I have it almost completed, but there's one part that I can't get to work. The inheritance works except when I get to Cube. For some reason, it won't calculate the Area or Volume (it just comes up with 0). I'm thinking it's a problem with the way I have the inheritance from Square to Cube. Help would be awesome!
package InheritanceTest;
import javax.swing.JOptionPane;
public class InheritanceTest {
public static void main(String[] args) {
String input = "";
Point point = new Point();
input = getinput("Set variable X");
point.setx(input);
input = getinput("Set variable Y");
point.sety(input);
System.out.println("Point, x = " + point.getx() + " y = " + point.gety());
Square square = new Square();
input = getinput("Set variable Side Length");
square.setSideLength(input);
System.out.println("Square, x = " + point.getx() + " y = " + point.gety()
+ " Area = " + square.getAreaOfSquare() + " Perimeter = "
+ square.getPerimeterOfSquare());
Cube cube = new Cube();
input = getinput("Set variable depth");
cube.setDepth(input);
System.out.println("cube, x = " + point.getx() + " y = " + point.gety()
+ " Depth = " + cube.getDepth() + " Area = " + cube.getAreaOfCube()
+ " Volume = " + cube.getVolumeOfCube());
}
private static String getinput(String string) {
String x = JOptionPane.showInputDialog(string);
return x;
}
}
package InheritanceTest;
public class Cube extends Square {
private int depth;
Cube() {
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d) {
super(x, y, sideLength);
this.depth = d;
}
public int getAreaOfCube() {
return (6 * sideLength * sideLength);
}
public int getVolumeOfCube() {
return (sideLength * sideLength * sideLength);
}
public String getDepth() {
return Integer.toString(depth);
}
public void setDepth(String i) {
depth = Integer.parseInt(i);
}
}
package InheritanceTest;
public class Point {
private int x;
private int y;
Point() {
x = 0;
y = 0;
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
public String getx() {
return Integer.toString(x);
}
public String gety() {
return Integer.toString(y);
}
public void setx(String input) {
x = Integer.parseInt(input);
}
public void sety(String input) {
y = Integer.parseInt(input);
}
}
package InheritanceTest;
public class Square extends Point {
protected int sideLength;
Square() {
super();
sideLength = 0;
}
Square(int x, int y, int l) {
super(x, y);
this.sideLength = l;
}
public int getAreaOfSquare() {
return sideLength * sideLength;
}
public int getPerimeterOfSquare() {
return sideLength + sideLength;
}
public String getSideLength() {
return Integer.toString(sideLength);
}
public void setSideLength(String input) {
sideLength = Integer.parseInt(input);
}
}
When you create cube (new Cube()) you aren't setting the side length (or x and y) for the Square Object it extends.
Cube(){
// This is the constructor called.
super();
depth = 0;
}
Cube(int x, int y, int sideLength, int d){
super(x, y, sideLength);
this.depth = d;
}
You probably want extract the x,y and length values into variables and use "new Cube(x, y, length, depth)"
Something like the following
String x = getinput("Set variable X");
String y = getinput("Set variable Y");
String sideLength = getinput("Set variable Side Length");
String depth getinput("Set variable depth");
Cube cube = new Cube(x, y, sideLength, depth);
Look at how you are defining getVolumeOfCube(). You are calculating volume with sideLength, but you never set sideLength to any non-zero value. Change sideLength to depth and you will get the value you are looking for.

Categories

Resources