I had to do a very basic "make a CAD project" for school and decided to make it a bit more challenging and add a way to interact more properly with the project. Basically, I have a Point
class with a constructor that takes x
and y
coordinates as input and also has some methods.
Point(double x, double y) {
this.x = x;
this.y = y;
}
I wanted the user to be able to create as many points as he/she desires - and thus I went to Hashmaps
(I tried lists too but I've read that Hashmaps
are better for this, even though I couldn't find concrete answers to what I want in my project). The relevant snippet from my code looks as follows:
Map<Integer, Point> pMap = new HashMap<Integer, Point>();
double[] singlePoints = new double[2]; // temporarily store x and y coordinates
...
...
...
switch (intInput) {
case 1:
System.out.println("Create point? y/n");
charInput = sc.next().charAt(0);
if(java.lang.Character.toLowerCase(charInput) == 'y') {
System.out.println("X coordinate: ");
singlePoints[0] = sc.nextDouble();
System.out.println("Y coordinate: ");
singlePoints[1] = sc.nextDouble();
pMap.put(pointCounter, new point(singlePoints[0], singlePoints[1]));
pointCounter ++;
break;
} else {
break;
}
case 2:
System.out.println("Which point shall be edited?: ");
int pointC2 = sc.nextInt();
System.out.println("X or Y coordinate? ");
char c2Input = java.lang.Character.toLowerCase(sc.next().charAt(0));
if(c2Input == 'x') {
???
}
}
The part with the question marks is where I want to change the x
coordinate only. Since I haven't given the new Point
(that is directly stored into the Hashmap
) a name, I can't access it with my getter and setter methods. How do I go on from here to change a single parameter (in this example it's 'x') of an object at a given index inside of the Hashmap
? If it's not possible, should I go back to normal Lists
, and if so, how would I do that? (Also, a quick note: We haven't gotten to Lists
or Hashmaps
in the lectures as of now so my knowledge is based on what I found on the internet and doesn't come from experience or university)
As user input the desired point in pointC2
you might find the stored key in your map.
Point selectedPoint = pMap.get(pointC2);
selectedPoint.setX(newX);
// pMap.get(pointC2).setX(newX);
You did store a key in
pMap.put(pointCounter, new point(singlePoints[0], singlePoints[1]));
Your key is pointCounter
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.