I'm making a Distance Formula calculator for practice, but I'm not able to get the program to run on the console when I instantiate the variables. What am I doing wrong here? Any feedback in terms of shortening the code or making it more efficient is also welcome. I've attached it here:
DistFormula.java
public class DistFormula {
public DistFormula() {
}
// Variables
private double x1, x2, y1, y2, diff1, diff2, part1, part2, ans;
// Get first X
public double X1(double x1) {
return x1;
}
// Get first Y
public double Y1(double y1) {
return y1;
}
// Get second X
public double X2(double x2) {
return x2;
}
// Get second Y
public double Y2(double y2) {
return y2;
}
// Set first difference
public double setFirstPart() {
diff1 = x2 - x1;
part1 = Math.pow(diff1, 2);
return part1;
}
// Get first difference
public double getFirstPart() {
return part1;
}
// Set second difference
public double setSecondPart() {
diff2 = y2 - y1;
part2 = Math.pow(diff2, 2);
return part2;
}
// Get second difference
public double getSecondPart() {
return part2;
}
// Set answer
public double setFinalAns() {
ans = Math.sqrt(part1 + part2);
return ans;
}
// Get answer
public double getFinalAns() {
return ans;
}
public String toString() {
return "Distance between coordinates: " + ans;
}
}
Main.java
public class Main {
public static void main(String[] arguments) {
DistFormula newFormula = new DistFormula();
newFormula.X1(10.1);
newFormula.Y1(18.2);
newFormula.X2(12.9);
newFormula.Y2(17.5);
newFormula.setFirstPart();
newFormula.setSecondPart();
newFormula.setFinalAns();
newFormula.toString();
}
}
First I think you would need some way to enter the values of each variable.
public void setX1(double x1) {
this.x1=x1;
}
Also if you want it to be even shorter you could pass these values via the constructor.
public DistFormula(double x1, double x2, double y1, double y2) {
this.x1=x1;
this.x2=x2;
this.y1=y1;
this.y2=y2;
}
You could of course break it down into small parts, but you could also have only one method that calculates the exact answer.
public double calculate() {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
If you use the first way I mentioned you need to then do (in Main):
DistFormula newFormula = new DistFormula();
newFormula.setX1(10.1);
newFormula.setY1(18.2);
newFormula.setX2(12.9);
newFormula.setY2(17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
If you use the second way:
DistFormula newFormula = new DistFormula(10.1,18.2,12.9,17.5);
double answer=newFormula.calculate();
System.out.println("Distance between coordinates: " + answer);
First lets try to fix your existing code. For any variable there are corresponding getters and setters but then why?
If a variable is private you cannot access it in other class and moreover in setter you can check the allowed value. For e.g mass of a person cannot be in negative so use of setters is to set the value along with checking some allowed limits. The return type of a setter is always void but not in your code. Getters are used to retrieve the value so return type is non void. You mixed the setter and getters in your code where setters are not setting any value but returning the value which is wrong.
I have modified the code:-
public class DistFormula {
public DistFormula() {
}
// Variables
private double x1, x2, y1, y2, diff1, diff2, part1, part2, ans;
// Get first X
public void setX1(double x1) {
this.x1=x1;
}
// Get first Y
public void setY1(double y1) {
this.y1=y1;
}
// Get second X
public void setX2(double x2) {
this.x2=x2;
}
// Get second Y
public void setY2(double y2) {
this.y2=y2;
}
// Set first difference
public void setFirstPart() {
diff1 = x2 - x1;
part1 = Math.pow(diff1, 2);
}
// Get first difference
public double getFirstPart() {
return part1;
}
// Set second difference
public void setSecondPart() {
diff2 = y2 - y1;
part2 = Math.pow(diff2, 2);
}
// Get second difference
public double getSecondPart() {
return part2;
}
// Set answer
public void setFinalAns() {
ans = Math.sqrt(part1 + part2);
}
// Get answer
public double getFinalAns() {
return ans;
}
public String toString() {
return "Distance between coordinates: " + ans;
}
}
public class Main {
public static void main(String[] arguments) {
//You are trying to achieve sqrt((x2-x1)^2 +(y2-y1)^2)
DistFormula newFormula = new DistFormula();
newFormula.setX1(10.1);
newFormula.setY1(18.2);
newFormula.setX2(12.9);
newFormula.setY2(17.5);
newFormula.setFirstPart();
newFormula.setSecondPart();
newFormula.setFinalAns();
System.out.println(newFormula.toString());
}
}
//Output is now coming as:-
Distance between coordinates: 2.886173937932363
In java for printing value in console you need to do it as:-
System.out.println(newFormula);
No need of calling toString method explicitly. See Why is the toString() method being called when I print an object?
A more efficient way is as under:-
public class TwoDimension {
private double x;
private double y;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
public class Main {
public static void main(String[] arguments) {
//You are trying to achieve sqrt((x2-x1)^2 +(y2-y1)^2)
TwoDimension newFormula1 = new TwoDimension();
newFormula1.setX(10.1);
newFormula1.setY(18.2);
TwoDimension newFormula2 = new TwoDimension();
newFormula2.setX(12.9);
newFormula2.setY(17.5);
Double x = newFormula2.getX() -newFormula1.getX();
Double y =newFormula2.getY() -newFormula1.getY();
Double z = Math.sqrt(Math.pow(x, 2)+Math.pow(y, 2)) ;
System.out.println("Distance between coordinates: " + z);
}
}
you need to call System.out.println(newFormula.toString());
Related
package polygongeneric;
import java.util.ArrayList;
public class Polygon {
private ArrayList <Point2d> p = null;
private int points = 0;
public Polygon() { }
public Polygon(int numPoints) {
p = new ArrayList<>();
}
public boolean addPoint(Point2d point) {
p.add(points, point);
points++;
return true;
}
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
p.add(points, a);
return true;
}
#Override
public String toString() {
String s = "";
for (int i=0; i<points; i++)
s += p.get(i).toString() + "\n";
return s;
}
}
I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.
This is what my code outputs
(0.1,0.9)
(0.5,0.5)
(0.2,0.5)
This is what it's supposed to output
(0.1,0.9)
(0.3,0.7)
(0.5,0.5)
(0.4,0.8)
(0.2,0.5)
Do you guys have any idea. What I'm doing wrong?
This is my Point2d class
package polygongeneric;
public class Point2d {
private double x = 0, y = 0;
public Point2d() { }
public Point2d(double x, double y) {
setX(x);
setY(y);
}
public void setX(double initX) {
if (initX >= 0 && initX <= 1)
x = initX;
}
public void setY(double y) {
if (y >= 0 && y <= 1)
this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public String toString() {
return "(" + x + "," + y + ")";
}
}
This is my main method
package polygongeneric;
public class PolygonGeneric {
public static void main(String[] args) {
Polygon p = new Polygon(5);
p.addPoint(new Point2d(.1, .9));
p.addPoint(.3, .7);
p.addPoint(new Point2d(.5, .5));
p.addPoint(.4, .8);
p.addPoint(new Point2d(.2, .5));
System.out.println(p);
}
}
You are not incrementing the position in your addPoint(double x, double y), so basically, you are replacing the existing point with a new point, so you are missing few point values and you need to correct the correct the code as shown below:
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x, y);
p.add(points, a);
points++;
return true;
}
Because you are simply adding the point at the end of the list, I suggest you can directly use arraylist.add(point); so that you will not get into these increment/other issues.
Also, you can change your constructor of Polygon class (which accepts int) as follows because you are not using the numPoints variable or else use an array with numPoints as the size instead of ArrayList.
public Polygon() {
p = new ArrayList<>();
}
You did not increment points in the addPoint(double x, double y) function.
Why not reuse the same method? and call the overloaded function
public boolean addPoint(Point2d point); instead of writing the same logic again and again.
public boolean addPoint(double x, double y) {
Point2d a = new Point2d(x,y);
return addPoint(a);
}
I'm getting confused about how to extract data from a custom class. The code groups Cartesian coordinates in a class called linesegment, with several instances of class CartesianCoordinate as its members. I am stuck trying to find the distance between two sets of cartesian coordinates.
How am I supposed to decode the linesegment class, into the cartesiancoordinate class, to then access the individual double values to print to screen from the main class?
Below are the three classes used within my program:
The main class:
public class lab3
{
public static void main(String [] args)
{
cartesiancoordinate one, two; //instantsiating one and two as type cartesiancoordiante
one = new cartesiancoordinate(5, 6); //putting the information for one and two into type cartesiancoordinate
two = new cartesiancoordinate(4.5, -6.5);
linesegment oneandtwo;
oneandtwo = new linesegment(one, two);
System.out.println(one.toString()); //dual X/Y statements using a toString method
System.out.println(two.toString());
System.out.println(oneandtwo.tostring());
System.out.println("X for one is: " + one.getx()); //individual X/Y statements using getter methods
System.out.println("Y for one is: " + one.gety());
System.out.println("X for two is: " + two.getx()); //individual X/Y statements using getter methods
System.out.println("Y for two is: " + two.gety());
double tester;
oneandtwo.test();
System.out.println("The test method returned the distance between the two cartesian coordinates to be: " + tester);
}
}
The cartesiancoordinate class:
class cartesiancoordinate
{
private double xposition;
private double yposition;
public cartesiancoordinate(double x, double y)
{
this.xposition = x;
this.yposition = y;
}
public double getx()
{
return this.xposition;
}
public double gety()
{
return this.yposition;
}
public String toString()
{
return "(" + this.xposition + " / " + this.yposition + ")";
}
}
The troublesome linesegment class:
class linesegment
{
private cartesiancoordinate startpoint, endpoint, s1, e1;
public cartesiancoordinate one, two;
public linesegment(cartesiancoordinate x, cartesiancoordinate y)
{
this.startpoint = x;
this.endpoint = y;
}
public cartesiancoordinate getstartpoint()
{
return this.startpoint;
}
public cartesiancoordinate getendpoint()
{
return this.endpoint;
}
public String tostring()
{
return ("The start point is " + this.startpoint + " and the end point is " + this.endpoint);
}
public double test()
{
double x1,x2,y1,y2;
cartesiancoordinate s1,e1;
getstartpoint() = s1;
getendpoint() = e1 ;
s1.getx() = x1;
s1.gety() = y1;
e1.getx() = x2;
e1.gety() = y2;
double tester;
tester = x1 + x2 + y1 + y2;
return tester;
}
}
Instead of:
double tester;
oneandtwo.test();
You want:
double tester = oneandtwo.test();
This is a problem.
getstartpoint() = s1;
getendpoint() = e1 ;
Your methods are return-ing values, so if you want to assign them to s1 and e1, then you can do that like so
s1 = getstartpoint();
e1 = getendpoint();
That won't fix the logic of your code, but it should at least compile.
Your linesegment class is broken:
class linesegment {
// a linesegment is nothing more than defined by a starting and ending point
private cartesiancoordinate startpoint, endpoint;
public linesegment(cartesiancoordinate x, cartesiancoordinate y) {
this.startpoint = x;
this.endpoint = y;
}
public cartesiancoordinate getstartpoint() {
return this.startpoint;
}
public cartesiancoordinate getendpoint() {
return this.endpoint;
}
public String toString() {
return ("The start point is " + this.startpoint + " and the end point is " + this.endpoint);
}
public double test()
{
double dx = endpoint.getx()-startpoint.getx();
double dy = endpoint.gety()-startpoint.gety();
return Math.sqrt(dx*dx+dy*dy);
}
}
Now in the main:
double tester = oneandtwo.test(); // get the distance
System.out.println("Distance is "+tester);
Please use standard naming conventions. Your classes must be spelled CartesianCoordinates, LineSegment, Lab3. Your variables: oneAndTwo, startPoint, endPoint...
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 7 years ago.
All, I'm having what appears to be simple problem not in loading the array but looping through the list after loading. Seems it always returns the last record loaded regardless. I've tried to limit what was stored in the ArrayList (itemVal=2) to see if that was the only value returned. But it's not. Code below:
import java.util.ArrayList;
public class testNewClass{
// element layout:
// String defTitle
// int seriesVal
// int itemVal
// double x coordinate
// double y coordinate
static String defTitle;
static int seriesVal;
static int itemVal;
static double xCoordinate;
static double yCoordinate;
/*
* Private constructor
*/
private static ArrayList<testNewClass> testList = new ArrayList<testNewClass>();
/*
* Methods
*/
public static void setAll(String title, int series, int item, double x, double y){
testNewClass newTest = new testNewClass();
newTest.defTitle = title;
newTest.seriesVal = series;
newTest.itemVal = item;
newTest.xCoordinate = x;
newTest.yCoordinate = y;
if (item == 2){
testList.add(newTest);
System.out.println("count of testList="+testList.size());
System.out.println("LOADING..series="+series+" item="+item+" x="+x+" y="+y);
}
}
public void setTitle(String title){
this.defTitle = title;
}
public static String returnNext(int Series, int Item){
String rtnVal = null;
System.out.println("testList(size)="+testList.size()+"..Series="+Series+"..Item="+Item);
for (int i=0; i<testList.size(); i++){
int nSeries = testList.get(i).seriesVal;
int nItem = testList.get(i).itemVal;
System.out.println("X="+testList.get(i).xCoordinate);
System.out.println("(i)="+i+" nSeries="+nSeries+" nItem="+nItem);
if (nSeries == Series && nItem == Item){
double lX = testList.get(i).xCoordinate;
double lY = testList.get(i).yCoordinate;
rtnVal = "x=" + lX + " y="+lY;
break;
}
}
return rtnVal;
}
}
I think this code is closer to the mark. Note that the last point is indeed the one it returns, and all the points in the series are independent.
package cruft;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Series encapsulates a List a Points
* Created by Michael
* Creation date 12/20/2015.
* #link https://stackoverflow.com/questions/34387750/arraylist-is-not-returning-the-array-but-the-last-element
*/
public class Series {
private List<Point> points;
public static void main(String[] args) {
Series series = new Series();
double x = 0.0;
double y = 0.0;
double dx = 0.1;
int numPoints = 21;
double minY = -1.0;
double maxY = +1.0;
Random random = (args.length > 0) ? new Random(Long.valueOf(args[0])) : new Random();
for (int i = 0; i < numPoints; ++i) {
series.addPoint(new Point(x, y));
x += dx;
y = minY + (maxY-minY)*random.nextDouble();
}
System.out.println(series);
System.out.println(series.getLastPoint());
}
public Series() {
this(null);
}
public Series(List<Point> points) {
this.points = (points == null) ? new ArrayList<Point>() : new ArrayList<Point>(points);
}
public void addPoint(Point p) {
if (p != null) {
this.points.add(p);
}
}
public Point getPoint(int index) {
return this.points.get(index);
}
public Point getLastPoint() {
return this.getPoint(this.points.size()-1);
}
#Override
public String toString() {
return "Series{" +
"points=" + points +
'}';
}
}
class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
#Override
public String toString() {
return "Point{" +
"x=" + String.format("%10.5f", x) +
", y=" + String.format("%10.5f", y) +
'}';
}
}
Ok, so I have made a toString() method for this Coordinate Class, but when I try to print a Coordinate using system.out.print(), it seems to ignore my method and just use the Object.toString() method, and just returns a memory address.
Here is my code for the toString method:
package spacetable;
public class Coordinate {
private int x;
private int y;
public Coordinate(){
x=0;
y=0;
}
public Coordinate(int x, int y){
this.x = x;
this.y = y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public double distTo(Coordinate xy){
double run = xy.getX() - this.getX();
double rise = xy.getY() - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
public double distTo(int x, int y){
double run = x - this.getX();
double rise = y - this.getX();
double dist = sqrt(run*run + rise*rise);
return dist;
}
#Override
public String toString(){
String Strx = Integer.toString(x);
String Stry = Integer.toString(y);
String result = "(" Strx + ", " + Stry + ")";
return result;
}
}
and my code that tries to print:
package spacetable;
public class CordinateTest {
public static void main(String[] args) {
Coordinate place = new Coordinate(2,3);
System.out.println(place);
}
}
And the output is:
spacetable.Coordinate#e53108
why is my toString() being ignored?
Your code works fine for me, take a look here
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static class Coordinate {
private int x = 3;
private int y = 5;
#Override
public String toString(){
String Strx = Integer.toString(x);
String Stry = Integer.toString(y);
String result = "(" + Strx + ", " + Stry + ")";
return result;
}
}
public static void main (String[] args) throws java.lang.Exception
{
Coordinate place = new Coordinate();
System.out.println(place);
}
}
are you sure you recompiled after you added the toString method. If you are using an IDE, please check that build automatically is set. If not build the code again
Also, can you paste the import command. just want to make sure you are importing your own Coordinate class and not a class of some third party jar
public class Coordinate {
private int x;
private int y;
public Coordinate(int x,int y)
{
this.x=x;
this.y=y;
}
public String toString()
{
String result = "("+ x + ", " + y + ")";
return result;
}
public static void main(String[] args) {
Coordinate place = new Coordinate(2,3);
System.out.println(place);
}
}
I want to create a triangle object and the get the area and perimeter of the triangle. I'm getting a NullPointerException at Triangle.area and at Demo.main. It seems like no values are being passed to the area method and perimeter method but I can't see where I've gone wrong with my code. Here's my code.
//POINTCLASS
public class Point {
private int x;
private int y;
public Point(int X, int Y){
this.x = X;
this.y = Y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public double distance(Point p){
double distance,dx,dy;
dx=x-p.x;
dy=y-p.y;
distance = Math.sqrt((dx*dx)+(dy*dy));
return distance;
}
public void translate(int dx, int dy){
x+=dx;
y+=dy;
}
public void scale(int factor){
x*=factor;
y*=factor;
}
public String toString(){
String attributes = "x = " + x + "," + " y = " + y;
return attributes;
}
}
//TRIANGL CLASS
public class Triangle {
private int sides = 3;
private Point point1,point2,point3;
private Point[] Points;
public Triangle(Point[] vertices){
Points = vertices;
}
public Triangle(int x1,int y1,int x2,int y2,int x3, int y3){
point1 = new Point(x1,y1);
point2 = new Point(x2,y2);
point3 = new Point(x3,y3);
Points[0]=point1;
Points[1]=point2;
Points[2]=point3;
}
public double perimeter(){
double side1=point1.distance(point2);
double side2=point2.distance(point3);
double side3=point1.distance(point3);
return side1+side2+side3;
}
//issue with code seems to be here
public double area(){
double side1=point1.distance(point2);
double side2=point2.distance(point3);
double side3=point1.distance(point3);
double s = perimeter()/2;
double area = Math.sqrt(s*(s-side1)*(s-side2)*(s-side3));
return area;
}
public String toString(){
String attributes = "Sides " + sides;
return attributes;
}
public void translate(int dx, int dy){
Points[0].translate(dx,dy);
Points[1].translate(dx, dy);
Points[2].translate(dx, dy);
}
public void scale(int factor){
vertices*=factor;
}
public Point getVertex(int i){
return vertices[i];
}
}
//MAIN CLASS
public class GDemo {
public static void main(String[] args) {
Point p1 = new Point(0,20);
Point p2 = new Point(20,0);
Point p3 = new Point(30,30);
Point[] vertices = {p1,p2,p3};
Triangle t = new Triangle(vertices);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
" perimeter: " + t.perimeter());
t.translate(10, 15);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
" perimeter: " + t.perimeter());
t.scale(2);
System.out.println("Triangle" + t.toString() + " area:" + t.area() +
"perimeter: " + t.perimeter());
}
}
You are calling the constructor Triangle(Point[] vertices) while creating the Triangle Object. So your these fields are remain uninitialized private Point point1,point2,point3; And that's why you are getting NullPointerException.
Fixed constructor should be something like this:
public Triangle(Point[] vertices){
Points = vertices;
// initialize point1, point2, point3 here.
if(vertices.length > 2){
this.point1 = vertices[0];
this.point2 = vertices[1];
this.point3 = vertices[2];
}
}
You call the constructor public Triangle(Point[] vertices) and you didn't set point1, point2, and point3 values - they stay null. Because this, when in method area you try calculate double side1 = point1.distance(point2); it throws NPE.
Try putting entire code in try-catch block and catch NullPointerException and write
e.printStackTrace();
eg:
try{
//your block of code
}catch(NullPointerException e){
e.printStackTrace();
}
It would display the line number of the error code