我在代码中对Excetpion做错了,因为当String layout
例如:
..b.
bbb. //<---Illegal
...
.x.
... //<---Illegal
..r
.rr //<---Illegal
.....
.y...
..y..
...y. //<---Illegal
传递给方法(一次只能传递一个布局),该方法应抛出异常,因为String layouts
形状必须在每个{{1}中至少有一个填充块},0th row
,0th column
和last row
。以下last column
是合法的:
String layout
我的代码只在看到第一行的第一个和最后一个字符时才处理异常。 smb请帮我解决...e
..e.
e...
a...a
.....
.....
a....
这个方法吗?提前谢谢!
throwing Exception
答案 0 :(得分:1)
有一些事情我还不清楚,所以我专注于将布局解析为二维char数组并检查你指定的约束。希望这能让您适应您的确切需求:
public static char[][] parseShape(String layout, char displayChar) throws Exception {
int height = 0;
Scanner data = new Scanner(layout);
ArrayList<String> lines = new ArrayList<String>();
// parse layout into an array of lines to determine dimensions
while (data.hasNextLine()) {
String line = data.nextLine();
lines.add(line);
height = line.length();
}
int width = lines.size();
char[][] temp = new char[height][width];
Boolean row0 = false;
Boolean col0 = false;
Boolean rowLast = false;
Boolean colLast = false;
// parse array of lines in char array and check for constraints
for (int w = 0; w < width; w++) {
String line = lines.get(w);
for (int h = 0; h < height; h++) {
char c = line.charAt(h);
if (c == displayChar) {
// we are looking at the display characters,
// check if we're in any of rows of columns that matter
if (h == 0)
row0 = true;
if (w == 0)
col0 = true;
if (h == height - 1)
rowLast = true;
if (w == width - 1)
colLast = true;
}
temp[h][w] = c;
}
}
// if any of the constraints are not true, the layout is invalid
if(!row0) {
throw new Exception("no block in Oth row");
}
if(!col0) {
throw new Exception("no block in Oth column");
}
if(!rowLast) {
throw new Exception("no block in last row");
}
if(!colLast) {
throw new Exception("no block in last column");
}
return temp;
}
基本上我们必须解析整个布局并累积满足的约束,而不是检查不满意。只有到最后我们才会知道他们是否都不满意。
答案 1 :(得分:0)
更简单的方法可能是使用正则表达式。
您的要求可表示为:
.
.
.
.
这些模式可以写成:
private static final LINE_STARTS_WITH_NON_DOT =
Pattern.compile("^[^.]", Pattern.MULTILINE);
private static final LINE_ENDS_WITH_NON_DOT =
Pattern.compile("[^.]$", Pattern.MULTILINE);
private static final FIRST_LINE_CONTAINS_NON_DOT =
Pattern.compile("^\\.*[^.]");
private static final LAST_LINE_CONTAINS_NON_DOT =
Pattern.compile("[^.]\\.*$");
要确保每个模式与layout
匹配,您可以写:
if (!LINE_STARTS_WITH_NON_DOT.matcher(layout).find()
|| !LINE_ENDS_WITH_NON_DOT.matcher(layout).find()
|| !FIRST_LINE_CONTAINS_NON_DOT.matcher(layout).find()
|| !LAST_LINE_CONTAINS_NON_DOT.matcher(layout).find()) {
throw new FitItException("Empty borders!");
}
(注意:上面假设layout
不以换行结束。如果 以换行结束,那么您需要将LINE_ENDS_WITH_NON_DOT
更改为Pattern.compile("[^.]\n")
,将LAST_LINE_CONTAINS_NON_DOT
更改为Pattern.compile("[^.]\\.*\n$")
。)