I am new trying to learn programing and java, I am currently working in a program but I need help starting it, I would really appreciate it if anyone could help me.
I have to Implement a class IrregularPolygon that contains an array list of Point2D.Double objects.
The Point2D.Double class defines a point specified in double precision representing a location in (x, y) coordinate space. For example, Point2D.Double(2.5, 3.1) constructs and initializes a point at coordinates (2.5, 3.1).
I'm going to be Using this declarations as a starting point for my lab work.
import java.awt.geom.*; // for Point2D.Double
import java.util.ArrayList; // for ArrayList
public class IrregularPolygon {
private ArrayList <Point2D.Double> myPolygon;
// constructors
public IrregularPolygon() { }
// public methods
public void add(Point2D.Double aPoint) { }
public double perimeter() { }
public double area() { }
}
I would like some tips on how to Write methods that compute the perimeter and the area of a polygon. To compute the perimeter, and to compute the distance between adjacent points, and total up the distances. The area of a polygon with corners is the absolute value of:
I suggest Math.hypot(point1.getX() - point2.getX(), point1.getY() - point2.getY()) for the distance of to adjacent points. For the perimeter (just as you stated) sum up all distances (don't forget to add the distance from the last to the first point). For the area see How do I calculate the surface area of a 2d polygon?.
I hope you can find this example helpful:
import java.awt.geom.*;
import java.util.ArrayList;
public class IrregularPolygon {
private ArrayList<Point2D.Double> myPolygon;
// constructors
public IrregularPolygon() {
this.myPolygon = new ArrayList<Point2D.Double>();
}
// public methods
public void add(Point2D.Double aPoint) {
this.myPolygon.add(aPoint);
}
public double perimeter() {
// compute perimeter
return 0;
}
public double area() {
// compute area
return 0;
}
#Override
public String toString() {
String result = "IrregularPolygon [";
for (Point2D.Double point : myPolygon) {
result += "|X: " + point.x + ". Y: " + point.y + "|";
}
result += "]";
return result;
}
public static void main(String[] args) {
IrregularPolygon irregularPolygon = new IrregularPolygon();
Point2D.Double point1 = new Point2D.Double(0, 2);
Point2D.Double point2 = new Point2D.Double(2, 4);
Point2D.Double point3 = new Point2D.Double(3, 5);
irregularPolygon.add(point1);
irregularPolygon.add(point2);
irregularPolygon.add(point3);
System.out.println(irregularPolygon.toString());
}
}
You can find in the toString() method how to use the ArrayList in Java, as well as in the add() method, so the implementation of the methods perimeter() and area() just depends on the specs you have. You just need to extrapolate that methods to complete the class.
Hope it helps.
Clemencio Morales Lucas.
this is what i have so far:
import java.awt.geom.*;
import java.util.ArrayList;
public class IrregularPolygon {
private ArrayList <Point2D.Double> myPolygon;
public IrregularPolygon()
{
myPolygon = new ArrayList < Point2D.Double > ();
}
public void add(Point2D.Double aPoint)
{
myPolygon.add(aPoint);
}
public void print()
{
for (Object element : myPolygon)
{
System.out.println(element);
}
}
public double distance(Point2D pt)
{
double distance = 0;
x.distance(y);
return distance;
}
public double perimeter()
{
double distance = 0;
for(int x = 0; x < aPoint; x++){ // cords given in groups might have to / by 2
get.point();
if(myPolygon[] != null){
get.nextPoint();
}
else{
distance += thePoint.distance(nextPoint)
}
}
return distance;
}
public double area()
{
double area = 0;
return area;
}
}
//that's irregular polygon. this is polygon application
import javax.swing.*;
import java.awt.geom.Point2D;
public class PolygonApplication
{
public static void main() {
String userInput;
int pointNumber = 1;
Point2D.Double nextPoint;
IrregularPolygon myPolygon = new IrregularPolygon();
do {
userInput = JOptionPane.showInputDialog("Enter x coordinate for point " + pointNumber);
if (userInput != null) {
double x = Double.parseDouble(userInput);
userInput = JOptionPane.showInputDialog("Enter y coordinate for point " +
pointNumber);
if (userInput != null) {
double y = Double.parseDouble(userInput);
nextPoint = new Point2D.Double(x,y);
myPolygon.add(nextPoint);
pointNumber += 1;
}
}
}
while (userInput != null);
myPolygon.print();
}
}
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) +
'}';
}
}
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());
So I just started working with ArrayList and awt.Point. What I am trying to accomplish here is to output an array of X and Y coordinates as the cannonball is in flight. However, when I run the program, I get a bunch of Point[x=0,y=0] within the array.
I think part of the problem maybe in return Point. I return a Point in bowling.Move() and bowling.getLocation(). It is possible that one is overriding the other? I feel that I am close to my result, but at a lose on how to get there.
import java.awt.Point;
import java.util.ArrayList;
import java.util.Scanner;
public class Cannonball {
public static void main(String[] args) {
//Part 1: Open Scanner
Scanner keyboard = new Scanner(System.in);
//Part 2: Create a new cannonball
Ball bowling = new Ball(0);
//Part 3: Ask user for initial angle and starting velocity
System.out.println("Alright, give us the angle at which to fire: ");
bowling.setAngle(keyboard.nextDouble());
System.out.println("And what is the initial velocity: ");
bowling.setVel(keyboard.nextDouble());
//Part 4: Return the points of the cannonball's flight
for(int i=0; i<bowling.shoot.size(); i++) System.out.println(bowling.shoot);
//Part x: Close input
keyboard.close();
}
}
class Ball{
private double xPos, yPos, deltaSec;
private double alpha, v;
private double yVel, xVel;
private static final double gravity = -9.81;
public Ball(double xPos){
this.xPos=xPos;
yPos=0;
}
public Point move(double deltaSec){
xPos += xVel*deltaSec;
yPos += yPos*deltaSec;
return new Point();
}
public void yVel(){
yVel=v*Math.sin(alpha)*(deltaSec*gravity);
}
public void xVel(){
xVel=v*Math.cos(alpha);
}
public Point getLocation(double xPos, double yPos){
return new Point();
}
public void setAngle(double aplha){
this.alpha=alpha;
}
public void setVel(double v){
this.v=v;
}
public ArrayList<Point> shoot = new ArrayList<Point>();
{
while(deltaSec<60){
move(deltaSec);
shoot.add(getLocation(xPos, yPos));
deltaSec++;
}
}
}
If you want to return a Point that represents the x and y coordinates at that timestamp, you should pass them to the point. Point() will create a point with coordinates 0/0.
You should either call the Point(x,y) constructor (which uses integer screen coordinates - intended to represent pixels!) or use Point2D resp. Point2D.Double( x, y).
Update:
Here's an example implementation of what I guess is intended for getLocation:
//Point version
public Point getLocation(double xPos, double yPos){
return new Point((int)xPos, (int)yPos); //Point only takes int coordinates
}
//Point2D version
public Point2D getLocation(double xPos, double yPos){
return new Point2D.Double( xPos, yPos );
}
move should do the same, if it needs to return a point at all.
UPDATE 2:
You seem to have added this code:
public ArrayList<Point> shoot = new ArrayList<Point>();
//I add this line to highlight the difference: the line above is no method signature
{
while(deltaSec<60){
move(deltaSec);
shoot.add(getLocation(xPos, yPos));
deltaSec++;
}
}
Note that this is not a method but an initializer block which will run at object creation time. I guess this it not intended.