简体   繁体   中英

How do I correct a NumberFormatException error?

The error Exception in thread "main" java.lang.NumberFormatException: For input string: "triangle" occurs when I try to run my program. However, if i delete all of the items in Arrays.asList() no results or errors are produced.

This is part of my Helper class containing the issues.

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;

Adding comments to clarify what is happening. The NFE occurs when you try to set the width of your rectangle object.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM