【发布时间】:2016-03-18 16:45:39
【问题描述】:
程序用于将程序参数解析为几何形状。
- 圆 (C):1 arg [半径]
- 五角大楼 (P):1 arg [边]
- Square, Rhombus, Rect (Q): 5 args [a,b,c,d,angleA](程序选择哪个 一个基于 args 生成)
我的问题是控制台中打印异常/错误的顺序。
public static void main(String[] args)
{
if (args.length > 0)
{
int readerIndex = 0; // currently read argument
for (char symbol : args[readerIndex++].toCharArray())
{
ShapeType type = null; // Enum for C, P or Q.
int toRead = 0; // How many args should we read.
int read = 0; // How many we alredy read.
try
{
type = ShapeType.bySymbol(symbol); // C, P or Q.
toRead = type.getDataFormatSize(); // number of args to read.
double[] vars = new double[toRead];
// converting
for (int i = 0; i < vars.length; ++i)
{
vars[i] = Double.valueOf(args[readerIndex + i]);
++read;
}
// This will create and print proper shape for given data.
System.out.println(ShapeFactory.generateShape(type, vars).toString());
}
catch (ShapeSymbolException e) // thrown if letter is not a shape symbol.
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e) // when we are out of args.
{
System.err.println("Too few arguments to generate " + type.name() + "!");
}
catch (NumberFormatException e) // When we can't convert to double.
{
System.err.println("Could not convert String to double while generating " + type.name() + ". Offender: " + args[readerIndex + read] + " | Dumping arguments: " + Arrays.toString(Arrays.copyOfRange(args, readerIndex, readerIndex + toRead)));
}
catch (ShapeGenException e) // When data passed to ShapeFactory cannot generate proper shape from it.
{
e.printStackTrace();
}
finally
{
readerIndex += toRead; // In any case (exception or not) - we will be skipping args that were supposed to be parsed to shape.
}
}
}
}
现在是数据输入:
- C 10
CIRCLE (C) | Radius = 10.0
- CQP 3 2 4 2 4 90 50
CIRCLE (C) | Radius = 3.0 QUADRILATERAL (Q) | RECTANGLE | Side A = 2.0 | Side B = 4.0 PENTAGON (P) | Side = 50.0
- CQPPQ 3 2 4 2 4 90 50 w2 2 2 2 2 90
CIRCLE (C) | Radius = 3.0 QUADRILATERAL (Q) | RECTANGLE | Side A = 2.0 | Side B = 4.0 PENTAGON (P) | Side = 50.0 Could not convert String to double while generating PENTAGON. Offender: w2 | Dumping arguments: [w2] QUADRILATERAL (Q) | SQUARE | Side = 2.0
“Could not conver...”部分随机打印在控制台中。它通常是它应该在的位置(按顺序排列第 4 个),但大约有 1/3 的时间它会出现在其他印刷品之一之前或之后。
我可以理解它稍后打印,但更早?我什么都想不出来。
为什么会这样?
【问题讨论】: