程序用于将程序参数解析为几何形状。
我的问题是在控制台中打印异常/错误的顺序。
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.
}
}
}
}
现在输入数据:
CIRCLE (C) | Radius = 10.0
CIRCLE (C) | Radius = 3.0 QUADRILATERAL (Q) | RECTANGLE | Side A = 2.0 | Side B = 4.0 PENTAGON (P) | Side = 50.0
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
“无法转换...”部分随机打印在控制台中。它通常是它应该在的位置(顺序排在第4位),但在其他打印之前或之后出现的次数约为1/3。
我可以理解它稍后打印,但更早?我什么都想不到。
为什么会这样?
答案 0 :(得分:6)
System.err
和System.out
是两个独立的流 - 订单仅在单个流中得到保证。由于两个流都以未定义的方式合并到您的控制台中,因此打印到两个流的文本的顺序可能会发生变化。如果您将所有内容打印到System.out
,那么您的输出就会很好。