I'm trying to subtract the coordinates of 2 vectors but I'm a beginner who can't figure out the OOP code I need. This is what I have so far.
public class practice {
public static class vector{
int a;
int b;
public vector(int a, int b){
this.a = a;
this.b = b;
}
public String coordinate(int x, int y){
x = this.a - a;
y = this.b - b;
return x + " " + y;
}
}
public static void main(String[] args) {
vector vec1 = new vector(2,3);
vector vec2 = new vector(3,4);
vector.coordinate?
}
}
How can I subtract the ints from the 2 vector objects?
I have done here some basic example which will allow you to subtract one vector from another one.
package com.test;
public class Vector {
private int x;
private int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
/**
* #return the x
*/
public int getX() {
return x;
}
/**
* #return the y
*/
public int getY() {
return y;
}
// if you don't want to create new vector and subtract from it self, then return type of this method would be void only.
public Vector subtract(Vector other) {
return new Vector(this.x - other.x, this.y - other.y);
}
#Override
public String toString() {
return this.x + " : "+ this.y;
}
public static void main(String[] args) {
Vector vector1 = new Vector(10, 10);
Vector vector2 = new Vector(5, 5);
Vector vector3 = vector1.subtract(vector2);
System.out.println(vector3);
}
}
I think you just want to call the coordinate method from vec1 using data from vec2.
if so this is one way of doing it:
System.out.println(vec1.coordinate(vec2.a,vec2.b));
in this case you also need to change your coordinate method to:
public String coordinate(int x, int y){
x = this.a - x;
y = this.b - y;
return x + " " + y;
}
You can create a method XsubtractY for which you input two vectors, then inside it gets each vectors a and b and subtracts them from each other to return your new vector. As follows:
public class practice {
public static class vector{
int a;
int b;
public vector(int a, int b){
this.a = a;
this.b = b;
}
public static vector XsubtractY(vector x, vector y){
vector newVector = new vector(x.a-y.a, x.b - y.b);
return newVector;
}
}
public static void main(String[] args) {
vector vec1 = new vector(2,3);
vector vec2 = new vector(3,4);
vector newVector = vector.XsubtractY(vec1, vec2);
System.out.println("New vector a: " + String.valueOf(newVector.a));
/* New vector a: -1 */
System.out.println("New vector b: " + String.valueOf(newVector.b));
/* New vector b: -1 */
}
}
The new vector becomes (-1,-1)
Related
public class Arrow {
protected static int x;
protected static int y;
public void setA(boolean a) {
this.a = a;
}
public void setB(boolean b) {
this.b = b;
}
public void setAb(boolean ab) {
this.ab = ab;
}
public Arrow( int x1, int y1) {
this.x=x1;
this.y=y1;
}
public double getySpeed(){
return (-ySpeed*Time+Time*Time/10);
}
public boolean getX(){
return x +Math.abs(xSpeed * Time)<canvasWidth-90;
}
public boolean getY(){
return y+getySpeed()<canvasHeight-110;
}
public Matrix getArrow(){
Matrix matrix = new Matrix();//1140,540
matrix.postRotate((int)getAngle(), arrowWidth/2, arrowHeight / 2);
if (a&&!ab) {
// here if i do sout(x) it will show 75 which is the value i gave it in the constructor
return a(x);
}
if(b&&!ab){
// here if i do sout(y) it will show 125 which is the value i gave it in the constructor
return (b(y));
}
if(ab){
x =x+(int) Math.abs(xSpeed * Time);
y = y+(int)getySpeed();
matrix.postTranslate(x,y );
}
return matrix;
}
public Matrix b(int yy ){
Matrix matrix = new Matrix();
matrix.postRotate((int)getAngle(), arrowWidth/2, arrowHeight / 2);
matrix.postTranslate(canvasWidth-90,yy );
return matrix;
}
public Matrix a(int xx ){
Matrix matrix = new Matrix();
matrix.postRotate((int)getAngle(), arrowWidth/2, arrowHeight / 2);
matrix.postTranslate(xx,canvasHeight-100 );
return matrix;
}
I am trying to make a Bitmap arrow stop from leaving the screen so I figured out the maximum x and y coordinates and the arrow moves until it reaches these coordinates.
In getArrow(), at the if(ab) block, what I think I am doing is changing x and y, but in reality, they're not changing.
- They stay the same value I gave them in the constructor.
How can I change the x and y in the class to the value I gave them at
if(ab) in getArrow()
Thank you :*)
The reason for the issue you are facing is because you have declared x and y as static making them class variables which means their values will be the same for all objects.
protected static int x;
protected static int y;
Just remove the term, static from their declaration.
Feel free to comment in case of any doubt/issue.
My plan is to create an array with only two values, which is {0,0} because I want to change its value in order to simulate how the coordinate moves.
I want to move the coordinate up to (0,1) when a random number is assigned to x,
let's say I have a line of if loop,
if(x=0){ //I would change the value from {0,0} to {0,1} }
I tried to write the code in this way,
public static int x = 0;
public static int y = 0;
public static void randomWalk(int [] moving_point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
moving_point[x,y] = moving_point[x,y+1];
}
}
but it is not correct,
is this a possible thing to do? and how?
Thank you!
The innermost code must be changed to:
moving_point[1] = moving_point[1] + 1;
The 1 gives you the index of the 'y' position in your moving_point array, but will not modify your fields.
public static int x = 0;
public static int y = 0;
public static void randomWalk(int [] moving_point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
moving_point[x,y] = moving_point[x,++y];
}
}
I would suggest to use Pre-Increment(++x) in this scenario. Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression.
moving_point[1]++;
inside the for.
I suggest you not to pass an array to the function since the method can't assume its length. You can either pass two ints or pass a class, there are severals already implemented: Point is just an example.
The arguably 'correcter' way to represent a Coordinate in Java is to create a Coordinate class:
public class Coordinate {
private int x;
private int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void moveUp(int distance) {
y += distance;
}
public void moveDown(int distance) {
y -= distance;
}
public void moveLeft(int distance) {
x -=distance;
}
public void moveRight(int distance) {
x += distance;
}
#Override
public String toString() {
return String.format("{%d,%d}", x, y);
}
}
public static void randomWalk(Coordinate point) {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
point.moveUp(1);
}
}
This allows you to succinctly represent multiple Coordinates in your software, as well as allowing you to write some very intuitive methods, such as the moveUp/Down/Left/Right in the above example.
Another good reason for doing this is that there are no constraints on your array, so someone could inadvertently add a third, fourth or fifth value, which clearly wouldn't make sense. Using a separate class makes the code more self-documenting.
Back to the example, you can now run:
Coordinate c = new Coordinate(0, 0);
System.out.println(c); // prints "{0,0}"
randomWalk(c);
System.out.println(c); // prints "{0,1}" IF you were lucky to get a random 0...
NB:
Here, Coordinate space is interpreted as like on a graph in school, increasing x to the right and increasing y going up. On computer screens the y-space is usually flipped (the origin is the top left of the screen), so as an exercise consider how you might correct that. (Hint, it only involves changingmoveUp() and moveDown())
Edit:
Following your comment, to be able to record the path, you'll probably want to use a LinkedHashMap instead of ArrayList (efficiency of lookups while keeping the ordering) and make Coordinate immutable by returning a new instance from each moveX operation. You will also need to implement equals() and hashCode().
public class Coordinate {
private final int x;
private final int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Coordinate moveUp(int distance) {
return new Coordinate(x, y+distance);
}
public Coordinate moveDown(int distance) {
return new Coordinate(x, y-distance);
}
public Coordinate moveLeft(int distance) {
return new Coordinate(x-distance, y);
}
public Coordinate moveRight(int distance) {
return new Coordinate(x+distance, y);
}
#Override
public String toString() {
return String.format("{%d,%d}", x, y);
}
#Override
public int hashCode() {
//we need to do something a bit more clever than "x+y", otherwise {1,0} might end up with the same hash as {0,1}
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
Coordinate other = (Coordinate)obj;
if(x != other.x) return false;
if(y != other.y) return false;
return true;
}
}
public class Walker {
private LinkedHashSet<Coordinate> path = new LinkedHashSet<>();
private Coordinate last;
public Walker(Coordinate startingPoint) {
path.add(startingPoint);
last = startingPoint;
}
public Set<Coordinate> getPath() {
return path;
}
public void randomWalk() {
int r = ThreadLocalRandom.current().nextInt(4);
if(r == 0) {
Coordinate nextStep = last.moveUp(1);
if(path.add(nextStep)) {
//Set returns "true" if the item was added, "false" otherwise.
last = nextStep;
} else {
//So if not added, we've already been there.
//take alternative action, retry, whatever...
}
}
}
}
Walker w = new Walker(new Coordinate(0,0));
for(int i=0; i<10; i++) {
w.randomWalk();
}
System.out.println(w.getPath());
This is Java code, I have created 4 classes 3 constructor and I am getting error of:
method area in class Rect cannot be applied to given types
There is a similar error for rest of 2 class as well. In this program basically I have created 4 classes, 1 for calculating area of rect, 1 for calculating area of Tri and 1 for calculating area of Square and last one is to access main function.
I have created 3 constructor for all the 3 classes rect tri and square and I am unable to spot the mistake in this program.
class Rect //1st class rect
{
double l, b; //variables
Rect(double l, double b) //constructor for rect
{
this.l = l;
this.b = b;
}
double area(double l, double b) //method to cal Rect area
{
return l * b;
}
}
class Square //square class
{
double s;
Square(Double s) //constructor for class
{
this.s = s;
}
double area(double s) //method to cal area for square
{
return s * s;
}
}
class Tri // class for triangle
{
double l, b, h; //variables
Tri(double l, double b, double h) // constructor for tri
{
this.l = l;
this.h = h;
this.b = b;
}
double area(double l, double b, double h) //method to cal area for tri
{
return 0.5 * l * b * h;
}
}
class Area3 {
public static void main(String args[]) {
Rect r = new Rect(10, 10); //constructor initialization for Rect
Square s = new Square(15.0);//constructor initialization for Square
Tri t = new Tri(10.0, 20.0, 30.0);//constructor initialization for Tri
System.out.print(" " + r.area() + "" + s.area() + "" + t.area()); //print areas
}
}
Your area method declarations state that the area methods take in arguments. With those declarations you can't say
Rect r = new Rect(1,4);
r.area();
Simply remove the double argument values from the area methods
You have to create area method without parameters, here the solution,
class Rect // 1st class rect
{
double l, b; // variables
Rect(double l, double b) // constructor for rect
{
this.l = l;
this.b = b;
}
double area(){
return this.l * this.b;
}
double area(double l, double b) // method to cal Rect area
{
return l * b;
}
}
class Square // square class
{
double s;
Square(Double s) // constructor for class
{
this.s = s;
}
double area(){
return this.s * this.s;
}
double area(double s) // method to cal area for square
{
return s * s;
}
}
class Tri // class for triangle
{
double l, b, h; // variables
Tri(double l, double b, double h) // constructor for tri
{
this.l = l;
this.h = h;
this.b = b;
}
double area(){
return 0.5 * this.l * this.b * this.h;
}
double area(double l, double b, double h) // method to cal area for tri
{
return 0.5 * l * b * h;
}
}
class Area3 {
public static void main(String args[]) {
Rect r = new Rect(10, 10); // constructor initialization for Rect
Square s = new Square(15.0);// constructor initialization for Square
Tri t = new Tri(10.0, 20.0, 30.0);// constructor initialization for Tri
System.out.print(" " + r.area() + " and " + s.area() + " and " + t.area()); // print
// areas
}
}
Hope this help, BTW it's work in my PC.
look at your contractors, they all receive an arguments.
and all your area()'s are getting also a arguments.
but!! in your main, you are calling the area() and do not give any values.
just delete from area()'s functions the receiving arguments.
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.
I am currently facing a problem and can't find the way. Here is the question...
Complete the Point class bellow:
public class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
So that the following code produces the output bellow:
public class TestClass{
public static void testEqual(Point p1, Point p2){
if (p1.equals(p2)){
System.out.println("The two points are equal\n"+p1);
}else{
System.out.println("The two points are not equal");
System.out.println("First Point: "+ p1);
System.out.println("Second Point: " + p2);
}
}
public static void main(String [] args){
Point p1 = new Point(2,3);
Point p2 = Point.clonePoint(p1);
Point p3 = new Point(1,1);
Point p4 = new Point(2,3);
testEqual(p1,p2);
testEqual(p1,p3);
testEqual(p1,p4);
testEqual(p2,p4);
}
}
Outputs
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are not equal
First Point: The X Coordinate is 2 and the Y Coordinate is 3
Second Point: The X Coordinate is 1 and the Y Coordinate is 1
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
The two points are equal
The X Coordinate is 2 and the Y Coordinate is 3
I can understand all the things but except this line Point p2 = Point.clonePoint(p1);
How can I solve it?
Add get methods for returning the point coordinates to your Point class:
public int getX()
{
return x;
}
public int getY()
{
return y;
}
Then add the following clonePoint() static method to your Point class:
public static Point clonePoint(Point p)
{
return new Point(p.getX(), p.getY());
}
Then add the following equals() method to your Point class:
public boolean equals(Point p)
{
return (p.getX() == getX()) && (p.getY() == getY());
}
This is all you need:
[note the last method 'clone' is a static (class) method that you access by prefixing it with the class name 'Point' followed by '.'].
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "The X Coordinate is " + x + " and the Y Coordinate is " + y;
}
#Override
public boolean equals(Object otherPoint) {
if (this == otherPoint) return true;
if (otherPoint == null || getClass() != otherPoint.getClass()) return false;
Point point = (Point) otherPoint;
return x == point.x && y == point.y;
}
#Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
public static Point clonePoint(Point p) {
return p != null ? new Point(p.x, p.y) : null;
}
}
I think your homework wants you to add a cloning method to the Point class like this:
public class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public static Point clonePoint(Point p){ return new Point(p.x,p.y); }
}