我应该读取 4 个坐标的输入 示例:0 1 1 1(其中 0 和 1 是第一个点的 X 和 Y 坐标,1 和 1 是第二个点的坐标) 我应该如何将这些整数存储在 Point 类型的数组列表中。 以下是我的方法:
public class Project1 {
private int m;
private int n;
private WeightedQuickUnionUF qu;
private int[][] grid;
private ArrayList<Point> connections;
/**
* initializes UnionFind structure, grid and connection list
* @param m
* @param n
*/
public Project1(int m, int n){
m=m;
n=n;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
grid = new int[i][j];
}
}
connections = new ArrayList<Point>();
int size = m*n;
qu = new WeightedQuickUnionUF(size);
}
public void read_input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of pairs of connections: ");
int no_of_connections = sc.nextInt();
for(int i=0; i < (no_of_connections * 4); i++){
Point coordinates = (Point)sc.nextInt();
connections.add(coordinates);
}
sc.close();
}
最佳答案
您可以创建自定义对象 TwoPoint
包含所有 4 个坐标。
使用 java.awt.Point
.
我会建议你使用 HashMap<TwoPoint>
其中键将是您输入的索引,值将是 TwoPoint
.
例如,如果您想检索第 4 个输入,只需调用 pointMap.get(4)
.
import java.awt.Point;
import java.util.HashMap;
import java.util.Scanner;
public class StorePoints
{
static int i = 0;
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
HashMap<Integer, TwoPoints> pointMap = new HashMap<Integer, StorePoints.TwoPoints>();
StorePoints sp = new StorePoints();
for (int i = 0; i < 3; i++)
{
System.out.println("Enter 4 coordinates: input ="+(i+1) +"out of 3");
sp.takeInput(sc,pointMap);
}
System.out.println(" Enter index of coordinate you want to see : [1-3]");
int index=sc.nextInt();
if(index<1||index>3)
System.out.println("Wrong index");
else
System.out.println("Input index="+index+", "+pointMap.get(index-1).toString());
sc.close();
}
public void takeInput(Scanner sc,HashMap<Integer, TwoPoints> pointMap)
{
int int1=sc.nextInt();int int2= sc.nextInt();int int3= sc.nextInt();int int4= sc.nextInt();
TwoPoints tp=new TwoPoints(int1,int2,int3,int4);
pointMap.put(i++, tp);
}
class TwoPoints
{
Point p1;
Point p2;
public TwoPoints(int int1, int int2, int int3, int int4)
{
p1 = new Point(int1, int2);
p2 = new Point(int3, int4);
}
// getters and setters
public Point getP1()
{
return p1;
}
public void setP1(Point p1)
{
this.p1 = p1;
}
public Point getP2()
{
return p2;
}
public void setP2(Point p2)
{
this.p2 = p2;
}
public String toString()
{
return "(" + p1 + "," + p2 + ")";
}
}
}
示例输出
Enter 4 coordinates: input =1out of 3
1 1 2 3
Enter 4 coordinates: input =2out of 3
2 2 3 4
Enter 4 coordinates: input =3out of 3
2 2 4 5
Enter coordinate number you want to see : [1-3]
1
Input index=1, (java.awt.Point[x=1,y=1],java.awt.Point[x=2,y=3])
关于java - 从用户输入创建点对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32747063/