[英]How do I fix the error of NumberFormatException everytime I run the program?
[英]How do I correct a NumberFormatException error?
线程“主”java.lang.NumberFormatException 中的错误异常:对于输入字符串:“三角形”在我尝试运行我的程序时发生。 但是,如果我删除Arrays.asList()
中的所有项目,则不会产生任何结果或错误。
这是我的Helper
class 的一部分,其中包含这些问题。
public static void display(ArrayList<String> shapes) throws IOException, FileNotFoundException{
java.util.List<String> list = Arrays.asList("rectangle", "circle","triangle");
for(int i = 0; i<list.size(); i++)
switch (list.get(i).toLowerCase())
{
case "rectangle":
Rectangle rectangle = new Rectangle();
rectangle.name = list.get(i+1);
rectangle.setWidth(Double.valueOf(list.get(i+2)));
rectangle.setLength(Double.valueOf(list.get(i+3)));
System.out.print(rectangle);
i = (i+3);
break;
添加评论以澄清正在发生的事情。 当您尝试设置矩形 object 的宽度时,会发生 NFE。
public static void display(ArrayList<String> shapes) throws IOException,
FileNotFoundException{
// index 0 = "rectangle", index 1 = "circle", index 2 = "triangle"
java.util.List<String> list = Arrays.asList("rectangle", "circle","triangle");
// on the first iteration i = 0
for(int i = 0; i<list.size(); i++)
// i is 0 so list.get(i).toLowerCase() = "rectangle"
switch (list.get(i).toLowerCase())
{
// since switch (list.get(i).toLowerCase()) evaluates to "rectangle" we enter
// this case statement
case "rectangle":
Rectangle rectangle = new Rectangle();
// i is 0 so list.get(i+1) = "circle", this probably isn't desired
// behavior
rectangle.name = list.get(i+1);
// i is 0 so list.get(i+2) = "triangle", "triangle" can't be converted to
// a double because it's not a number a NumberFormatExpection is thrown
rectangle.setWidth(Double.valueOf(list.get(i+2)));
// i is 0 so we can't determine what element is in the list at index 3
// because it doesn't exist an ArrayIndexOutOfBoundsException is thrown
rectangle.setLength(Double.valueOf(list.get(i+3)));
System.out.print(rectangle);
// not sure what this is doing
i = (i+3);
break;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.