Java - 将字符串转换为矩形
Java - Converting a string into a rectangle
我正在从文件中读取一个字符串,并从中获取一个字符串变量。我想将它转换成一个矩形变量。我正在使用扫描仪 class 从文件中读取。这是我的代码。
r = new Rectangle[ed];
for(int i = 0;i < ed; i++){
String rs = roomInfo.nextLine();
r[i] = new Rectangle(rs);
}
在我的代码中,我从文件中读入一个字符串,然后您可以看到我是如何尝试将它转换为一个矩形的。
您应该以某种方式将 String
解析为数字,然后您可以从中创建 Rectangle
个对象。
比如说,你的字符串看起来像这样:
"0, 0, 20, 20"
那是
"<x>, <y>, <width>, <hight>"
那么你需要做的是:
String[] split = str.split("[,]");
Rectangle rect = new Rectangle(split[0], split[1], split[2], split[3]);
其他字符串格式需要其他技术。
您可以使用 flattenToString
将字符串转换为矩形
String str = rect.flattenToString();
字符串格式会是这样
str = "0 -593 933 1066"
使用这种格式,将字符串恢复为 rect 是
Rect rect = Rect.unflattenFromString(str);
我正在从文件中读取一个字符串,并从中获取一个字符串变量。我想将它转换成一个矩形变量。我正在使用扫描仪 class 从文件中读取。这是我的代码。
r = new Rectangle[ed];
for(int i = 0;i < ed; i++){
String rs = roomInfo.nextLine();
r[i] = new Rectangle(rs);
}
在我的代码中,我从文件中读入一个字符串,然后您可以看到我是如何尝试将它转换为一个矩形的。
您应该以某种方式将 String
解析为数字,然后您可以从中创建 Rectangle
个对象。
比如说,你的字符串看起来像这样:
"0, 0, 20, 20"
那是
"<x>, <y>, <width>, <hight>"
那么你需要做的是:
String[] split = str.split("[,]");
Rectangle rect = new Rectangle(split[0], split[1], split[2], split[3]);
其他字符串格式需要其他技术。
您可以使用 flattenToString
将字符串转换为矩形String str = rect.flattenToString();
字符串格式会是这样
str = "0 -593 933 1066"
使用这种格式,将字符串恢复为 rect 是
Rect rect = Rect.unflattenFromString(str);