gpt4 book ai didi

java - 如何划分字符串 (x1,y1)(x2,y2) 格式

转载 作者:行者123 更新时间:2023-12-02 06:23:44 25 4
gpt4 key购买 nike

如何分割字符串(x1,y1)(x2,y2)格式

例如字符串是(100,200) (300,600),我正在创建对象(点)

class point{
int x;
int y;
}

我尝试使用StringTokenizer,但这不是正确的方法。

最佳答案

我会做这样的事情 -

public static class Point {
public Point(int x, int y) {
this.x = x;
this.y = y;
}

private int x;
private int y;

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}

public String toString() {
return "(" + String.valueOf(x) + ", "
+ String.valueOf(y) + ")";
}

public static Point[] fromString(String in) {
if (in == null) {
return null;
}
List<Point> al = new ArrayList<Point>();
int p = 0;
for (;;) {
int openPos = in.indexOf('(', p);
if (openPos > -1) {
int closePos = in.indexOf(')', openPos + 1);
if (closePos > -1) {
String str = in.substring(openPos + 1,
closePos);
String[] t = str.split(",");
p = closePos + 1;
if (t.length != 2) {
continue;
}
al.add(new Point(Integer.valueOf(t[0]
.trim()), Integer.valueOf(t[1].trim())));
} else {
break;
}
} else {
break;
}
}
return al.toArray(new Point[al.size()]);
}
}

public static void main(String[] args) {
Point[] pts = Point
.fromString("(100,200) (300,600)");
System.out.println(Arrays.toString(pts));
}

当我运行它时,输出 -

[(100, 200), (300, 600)]

关于java - 如何划分字符串 (x1,y1)(x2,y2) 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20779608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com