NumberFormatException的Java错误

时间:2014-02-17 20:14:13

标签: java

当我运行以下代码并输入5x5的大小时,我收到此错误。不确定为什么?

当我输入10x10时,似乎运行正常,但我不确定输出是否正确。

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)"

这是我的代码

    import java.util.Scanner;

    public class CheckerBoard {

        public static void main(String [] args){

        Scanner userInput = new Scanner(System.in);

        System.out.println("What two colors would you like your board to be?");

        String colorOne = userInput.next();
        String colorTwo = userInput.next();

        do {    
            System.out.println("How big should the checker board be? (Square sizes only please)" + "\n"
                + "Please enter it like 4x4 with whatever numbers you choose.");

            String boardSize = userInput.next();

            int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));
            System.out.println(boardSize.indexOf("x"));
            int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));
            System.out.println(intOne);

        } while(false);
        }
    }

    //keep in mind that this program is not done yet, this is just a current issue I am having atm.

5 个答案:

答案 0 :(得分:2)

我认为更安全的方法是分开x

String boardSize = userInput.next();
String[] split = boardSize.split("x");
int intOne = Integer.parseInt(split[0]);
int intTwo = Integer.parseInt(split[1]);

显然对BAD INPUT进行消毒!

答案 1 :(得分:1)

问题在于:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));

您正在将x的子字符串带到length - 1。您应该从x转到length,因为substring不包含第二个索引。

因此,您在5x5上收到错误,因为x后面只有一个字符。所以你试图parseInt一个空字符串。您在10x10上没有例外,但您只使用10x1

因此,您应该将该行更改为:

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

答案 2 :(得分:0)

在运行该行时,您的代码未考虑 boardSize 字符串实际上可能为空;

int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));

当您执行“indexOf”时,搜索不存在的内容 - 您将返回-1,这对您的子字符串的参数无效。

答案 3 :(得分:0)

你试过这个吗?

        int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));

你看起来可能会解决解析问题的时间越久。

答案 4 :(得分:0)

更改
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()-1));

int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));
请记住,传递给String.substring的第二个索引不会包含在返回值中。