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:
String
, not a Character
new coords(65,72)
should be new Coords(65,72)
)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. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With