gpt4 book ai didi

java - 当字符串形状非法时抛出异常

转载 作者:行者123 更新时间:2023-12-01 11:37:10 26 4
gpt4 key购买 nike

我在代码中对 Excetpion 做了一些错误的事情,因为当 String 布局 时,例如:

..b.
bbb. //<---Illegal

...
.x.
... //<---Illegal

..r
.rr //<---Illegal

.....
.y...
..y..
...y. //<---Illegal

被传递到方法中(一次只能传递一个布局),该方法应该抛出异常,因为形状的字符串布局必须在每个布局中至少有一个填充 block 第 0 行第 0 列最后一行最后一列。以下字符串布局是合法的:

...e
..e.
e...

a...a
.....
.....
a....

我的代码仅在看到第一行的第一个和最后一个字符时处理异常。 smb 可以帮我解决一下关于抛出异常的方法吗?预先感谢!

public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];

Scanner data2 = new Scanner(layout);
while(data2.hasNextLine())
{
String line2 = data2.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");

else {

for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
// System.out.println(line2.charAt(c));

if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));

}
}
}
result = new CreateShape(height, width, displayChar, layout);
return result;
}

最佳答案

还有一些事情我还不清楚,所以我集中精力将布局解析为二维字符数组并检查您指定的约束。希望这能让您根据自己的具体需求进行调整:

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

基本上,我们必须解析整个布局并累积满足的约束,而不是检查不满足的约束。只有到最后我们才会知道他们是否都不满意。

关于java - 当字符串形状非法时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29861042/

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