有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java存储X和Y坐标

嗨,我是新来这个网站的,我需要一个项目的帮助。我的问题是,我似乎无法存储字符串和两个整数(作为坐标)。我看过其他代码,但没有看到值是如何存储的。下面是我一直在使用的代码。代码似乎很好,但在尝试存储值时,我不能将乘法整数。谢谢你抽出时间

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");
    }

}

共 (2) 个答案

  1. # 1 楼答案

    java中有一个名为class Point的类

    http://docs.oracle.com/javase/7/docs/api/java/awt/Point.html

    这与Java docs API 10中提供的信息相同:

    https://docs.oracle.com/javase/10/docs/api/java/awt/Point.html

    在(x,y)坐标空间中表示位置的点,以整数精度指定

    你可以在这个链接中看到一个例子,以及其他相关的重要主题: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);
      }
    }
    

    我希望这能帮助你

  2. # 2 楼答案

    添加到@assylias

    1. 使您inner classstatic以插入新对象,就像您所拥有的或new Outer().new Inner()
    2. 照顾Java Naming Convention

    代码如下:

    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());
        }
    }