So I have this Polyline class that uses another class (Point) to create a polyline.
The class Point just defines a point with a x and y value and a name to it (Point A, Point B, etc)
public class Polyline
{
private Point [] corner;
public Polyline ()
{
this.corner = new Point[0];
}
public Polyline (Point [] corner)
{
this.corner = new Point [cornerlength];
for (int i = 0; i < corner.length; i++)
this.corner[i] = new Point (corner[i]);
}
Now my question is, how do I give these corners their values? I made a programme called PolylineTest and I would like to give it some values and print it out, but I haven't managed to figure out how to do it.
I figured it would be something like this:
Polyline [] p1 = new Polyline[0];
but I can't figure out how to give it a value.
Could anyone give me a nudge to the right direction?
Thank you in advance
(the code currently does not compile)
Asuming your Point class looks something like:
public class Point {
public String name;
public int x;
public int y;
public Point(String name, int x, int y) {
this.name = name;
this.x = x;
this.y = y;
}
public Point(Point p) {
this.name = p.name;
this.x = p.x;
this.y = p.y;
}
public String toString() {
return name + "[" + x + ", " + y + "]";
}
}
and you add this method to your Polyline class:
public String toString() {
return "Polyline " + Arrays.toString(corner);
}
the usage looks like:
public class PolylineTest {
public static void main(String[] args) {
Point[] points = new Point[] {
new Point("A", 4, 2),
new Point("B", 8, 5),
new Point("C", 1, 7)
};
Polyline polyline = new Polyline(points);
System.out.println(polyline);
}
}
Related
I have a LinkedList with different types of data which I need to handle in order to make a comparison and add the values that agree with the scope. More explanation will be given below,
LinkedList is filled with data of Record class:
class Record {
public int id;
public Point location;
public double score;
(...)
}
Point class:
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double dist(Point p) {
return Math.sqrt((this.x-p.x)*(this.x-p.x)+(this.y-p.y)*(this.y-p.y));
}
RankList class:
class RankList {
private Node first;
private int nodeCount;
private Record record;
public static void main(String[] args) {
RankList list = new RankList();
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
System.out.println(list.insert(record));
double maxDist=point.dist(point);
Point point1 = new Point(1.4, 9.2);
Record record1 = new Record(2, point1, 7.5);
if((point1.dist(point)>maxDist)) maxDist=point1.dist(point);
System.out.println(list.insert(record1));
Point point2 = new Point(2.2, 1.2);
Record record2 = new Record(3, point2, 6.0);
if((point2.dist(point1)>maxDist)) maxDist=point2.dist(point1);
System.out.println(list.insert(record2));
list.nearest(point1,maxDist);
I 've inserted some values to the list and let's say that I have some distance values between the given points like:
Distance between two points:
A->B = 3.2455
B->C = 7.345
C->D = 2.111
D->E = 8.056
From that the maxDist value is 8.059
Now I have to write the method public RankList nearest (Point p,double maxDist) which finds all the distance values between the scope (<=maxDist) and return them in a list with the rest node values. So I need to calculate the distance with the pointers of the LinkedList and the given Point p argument, and add them to a new list.
My problem is if can I access the LinkedList which is already fulfilled with values and copy what I need to the new list structure.
Method nearest:
public RankList nearest (Point p,double maxDist){
RankList nearList = new RankList();
Node current = first;
System.out.print("HEAD -> ");
while (current != null) {
System.out.print(current);
System.out.print(" -> ");
current = current.getNext();
}
System.out.println("null");
return null;
}
I've tried to run the whole LinkedList with the traditional way but I stack on how to make the comparisons and add them to the new list.
Any suggestions?
I'm a little bit confused with your code. I cant find any LinkedList in it. Your class RankList seems to have only three fields and none of them is of the List type. I'm not sure what does the insert method does.
It is not the best idea to have fields in the class with the main method. It would be better if you prepare another class that runs the program.
I'd like to show how I'd write the code:
import java.util.Comparator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
// I don't want the list to be a field of the class.
RecordsList list = new RecordsList();
// Following code blocks could be extracted as separate methods
Point point = new Point(5.4, 3.2);
Record record = new Record(1, point, 8.2);
list.add(record);
double maxDist = point.dist(point);
Point point1 = new Point(1.4, 9.2);
Record record1 = new Record(2, point1, 7.5);
if((point1.dist(point)>maxDist)) maxDist=point1.dist(point);
list.add(record1);
Point point2 = new Point(2.2, 1.2);
Record record2 = new Record(3, point2, 6.0);
if((point2.dist(point1)>maxDist)) maxDist=point2.dist(point1);
list.add(record2);
Point farPoint = new Point(50, 50);
Record recordWithFarPoint = new Record(4, farPoint, 5);
list.add(recordWithFarPoint);
RecordsList nearestList = list.nearest(point1, 20);
for (Record rec : nearestList.getList()) {
System.out.println(rec.id + " " + rec.location.x + " " + rec.location.y + " " + rec.score);
}
/*
* On console:
* 2 1.4 9.2 7.5
* 1 5.4 3.2 8.2
* 3 2.2 1.2 6.0
*/
}
}
/**
* This class is so-called wrapper on ArrayList.
*/
class RecordsList {
// This may be called delegate.
private ArrayList<Record> list = new ArrayList<>();
public void add(Record record) {
this.list.add(record);
}
// This creates shallow copy.
public ArrayList<Record> getList() {
return new ArrayList<>(list);
}
public RecordsList nearest(Point p, double maxDistance) {
RecordsList list = new RecordsList();
List<Record> records = this.getList().stream()
.sorted(Comparator.comparingDouble(oldListElement -> oldListElement.location.dist(p)))
.filter(element -> element.location.dist(p) <= maxDistance)
.collect(Collectors.toList());
for (Record record : records) {
list.add(record);
}
return list;
}
}
class Record {
public int id;
public Point location;
public double score;
public Record(int id, Point location, double score) {
this.id = id;
this.location = location;
this.score = score;
}
}
class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double dist(Point p) {
return Math.sqrt((this.x - p.x) * (this.x - p.x) + (this.y - p.y) * (this.y - p.y));
}
}
There are some concepts that may be new for you. The most complicated one is propably streamApi. You may read more about it i.e. here: https://www.baeldung.com/java-8-streams
If you have any questions, or I misunderstood your problem, feel free to ask.
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) +
'}';
}
}
Hi im new to this site and need help with a program im working on. the problem im having is that i cant seem to store string and two integers (as the coordinates). i have looked at other code but dont see how the values are stored. below is the code ive been using. the code seems to be fine but when trying to stored the values i cant put multiply integers. thanks for your time
import java.util.HashMap;
public class map {
class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, Character> map = new HashMap<Coords, Character>();
map.put(new coords(65, 72), "Dan");
}
}
There is a class in java called Class Point.
http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html
This is the same information provided on Java docs API 10:
https://docs.oracle.com/javase/10/docs/api/java/awt/Point.html
A point representing a location in (x,y) coordinate space, specified in integer precision.
You can see an example, and also other important topics related in this link: http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/Pointclass.htm
import java.awt.Point;
class PointSetter {
public static void main(String[] arguments) {
Point location = new Point(4, 13);
System.out.println("Starting location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
System.out.println("\nMoving to (7, 6)");
location.x = 7;
location.y = 6;
System.out.println("\nEnding location:");
System.out.println("X equals " + location.x);
System.out.println("Y equals " + location.y);
}
}
I hope this can help you!
There seems to be several issues:
"Dan" is a String, not a Character
case is important in Java (new coords(65,72) should be new Coords(65,72))
Coords needs to be static to be instantiated without a reference to an instance the enclosing map class.
This should work:
static class Coords {
...
}
Map<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
ps: although you are allowed to name a local variable map within a class map, it is not a good idea to have such name collision. In Java, classes generally start in upper case, so you could rename your class Map. But it happens that Map is a standard class in Java. So call your class Main or Test or whatever is relevant. ;-)
Adding to #assylias
Make you inner class static in order to insert new objects like you have or new Outer().new Inner() .
Take care of Java Naming Convention
Code like:
public class XYTest {
static class Coords {
int x;
int y;
public boolean equals(Object o) {
Coords c = (Coords) o;
return c.x == x && c.y == y;
}
public Coords(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int hashCode() {
return new Integer(x + "0" + y);
}
}
public static void main(String args[]) {
HashMap<Coords, String> map = new HashMap<Coords, String>();
map.put(new Coords(65, 72), "Dan");
map.put(new Coords(68, 78), "Amn");
map.put(new Coords(675, 89), "Ann");
System.out.println(map.size());
}
}
package Lecture3;
import java.util.Scanner;
public class lecture9 {
private int nInleste;
public lecture9() {/*
* tabell/ // T/*chapter 6 in the books.
**/
}
public static void main(String[] args) {
Scanner inn = new Scanner(System.in);
int nInleste = 3;
double[] tall = new double[nInleste];
double sum = 0;
for (int i = 0; i < nInleste; i++) {
System.out.println("Leste en tall!");
tall[i] = inn.nextDouble();
sum += tall[i];
}
System.out.println(sum);
double snitt = nInleste / nInleste;
System.out.println("Gjennomsnittsverdien:" + snitt);
for (int i = 0; i < nInleste; i++) {
double aavik = tall[i] - snitt;
int avvivk = 0;
System.out.println(i + 1 + " Tal sitt avvik fra gjennomsnittet " + avvivk);
}
}/* end of the main methods */
}
if you have problem with your code you can try this , simple code to store string and two int values into a map
class MyCoord{
private int X;
private int Y;
public MyCoord() {
this(0,0);
}
public MyCoord(int X, int Y) {
this.X = X;
this.Y = Y;
}
public int getX() {
return X;
}
public int getY() {
return Y;
}
public void setX(int X) {
this.X = X;
}
public void setY(int Y) {
this.Y = Y;
}
}
//main class begins
public class PointDemo{
public static void main(String[] args) {
Map <String,MyCoord> multiplePoints=new HashMap<String, MyCoord>();
multiplePoints.put("point1", new MyCoord(10, 20));
multiplePoints.put("point2", new MyCoord(100, 2000));
MyCoord coord=multiplePoints.get("point1");
System.out.println(coord.getX() +" : "+coord.getY());
}
}