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());
}
}
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 am trying to print the array that I have created in the Lab12 class using nested for loop and the getX() and getY() methods that I created in the MyPoint class. However my loop is just giving me the reference. how do i get the values to print
pt[0][0] = (0.5, 1.2)
pt[0][1] = (0.0, 3.14)
pt[0][2] = (15.0, 27.5)
pt[1][0] = (6.6, 7.7)
pt[1][1] = (1.2, 2.1)
pt[1][2] = (12.0, 127.0)
public class MyPoint {
private double x;
private double y;
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
public class Lab12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyPoint [][]pointMatrix = {
{new MyPoint(0.5,1.2), new MyPoint(0.0,3.14), new MyPoint(15.0,27.5)},
{new MyPoint(6.6,7.7), new MyPoint(1.2,2.1), new MyPoint(12.0,127.0)}
};
for (int i=0; i<pointMatrix.length; i++) {
for (int j=0; j<pointMatrix[i].length; j++){
System.out.print(pointMatrix[i][j] + " ");
}
System.out.println();
}
}
The best option, as #Lashane mentioned, is to implement the toString() method:
public class MyPoint {
// ...
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
Inside your loop:
System.out.println("pt[" + i + "][" + j + "] = " + pointMatrix[i][j]);
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);
}
}
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);
}
}