向Shape对象数组添加元素时抛出NumberFormatException的原因是什么
错误原因
- 核心触发
NumberFormatException的原因:你判断形状类型时,shapes[i]存储的是Cylinder这类类型字符串,调用setHeight时你直接对当前i位置的shapes[i]做数值转换,相当于尝试把类型字符串转成Double,直接触发异常。 - 后置自增逻辑混乱:你对
i执行i++后,继续用新的i下标操作shh[i],此时shh的新下标位置还没初始化对象,后续会触发空指针异常。 - 循环边界错误:
for(int i = 0; i <= shapes.length; i++)数组下标范围是0 ~ shapes.length-1,<=会导致数组下标越界。 - SquarePrism分支判断逻辑错误:写死了
shapes[8].equals("SquarePrism"),无论循环变量i是多少都判断固定下标8的内容,完全不符合预期。 - 数组长度不匹配:
shh数组长度是numberOfShapes,但循环中i每次处理完一个形状会自增3次(类型+2个参数),很容易超过shh的数组长度触发越界。
修复方案
首先明确shapes数组的存储规则:每3个元素为一组,第一个是形状类型,第二个是高度,第三个是边长/半径,shh的长度应该为shapes.length / 3。修复后的代码如下:
// 先修正shh数组的初始化长度,每3个shapes元素对应一个Shape对象 Shape[] shh = new Shape[shapes.length / 3]; int shapeIndex = 0; // 单独维护shh数组的下标 for(int i = 0; i < shapes.length; ) { // 去掉for循环的i自增,在内部手动控制下标移动 if (shapes[i].equals("Cylinder")) { Cylinder cylinder = new Cylinder(); // 取i+1位置的高度,i+2位置的半径 cylinder.setHeight(Double.parseDouble(shapes[i+1])); cylinder.setRadius(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = cylinder; // 下标移动3位到下一个形状的类型位置 i += 3; shapeIndex++; } else if(shapes[i].equals("Cone")) { Cone cone = new Cone(); cone.setHeight(Double.parseDouble(shapes[i+1])); cone.setRadius(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = cone; i += 3; shapeIndex++; } else if (shapes[i].equals("OctagonalPrism")) { OctagonalPrism prism = new OctagonalPrism(); prism.setHeight(Double.parseDouble(shapes[i+1])); prism.setEdgeLength(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = prism; i += 3; shapeIndex++; } else if(shapes[i].equals("PentagonalPrism")) { PentagonalPrism prism = new PentagonalPrism(); prism.setHeight(Double.parseDouble(shapes[i+1])); prism.setEdgeLength(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = prism; i += 3; shapeIndex++; } else if(shapes[i].equals("Pyramid")) { Pyramid pyramid = new Pyramid(); pyramid.setHeight(Double.parseDouble(shapes[i+1])); pyramid.setEdgeLength(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = pyramid; i += 3; shapeIndex++; } else if(shapes[i].equals("SquarePrism")) { SquarePrism prism = new SquarePrism(); prism.setHeight(Double.parseDouble(shapes[i+1])); prism.setEdgeLength(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = prism; i += 3; shapeIndex++; } else if(shapes[i].equals("TriangularPrism")) { TriangularPrism prism = new TriangularPrism(); prism.setHeight(Double.parseDouble(shapes[i+1])); prism.setEdgeLength(Double.parseDouble(shapes[i+2])); shh[shapeIndex] = prism; i += 3; shapeIndex++; } else { // 未知类型兜底处理,避免死循环 i++; } }
内容的提问来源于stack exchange,提问作者Bronson3123
相关产品推荐
相关产品推荐

