NumberFormatException的Java错误
当我运行下面的代码并输入5x5作为大小时,我得到了这个错误。不知道为什么 当我输入10x10时,它似乎运行正常,但我不确定输出是否正确NumberFormatException的Java错误,java,Java,当我运行下面的代码并输入5x5作为大小时,我得到了这个错误。不知道为什么 当我输入10x10时,它似乎运行正常,但我不确定输出是否正确 Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseI
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.
问题在于:
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()));
在运行该行时,您的代码没有考虑boardSize字符串实际上可能是空的
int intOne = Integer.parseInt(boardSize.substring(0,boardSize.indexOf("x")));
当您执行“indexOf”时,搜索不存在的内容——您将返回-1,它作为子字符串的参数无效 你试过这个吗
int intTwo = Integer.parseInt(boardSize.substring(boardSize.indexOf("x")+1, boardSize.length()));
可能你看的时间越长,解析问题就解决了。我认为更安全的方法是在
x上拆分
String boardSize = userInput.next();
String[] split = boardSize.split("x");
int intOne = Integer.parseInt(split[0]);
int intTwo = Integer.parseInt(split[1]);
显然,对错误输入进行清理 改变
intinttwo=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的第二个索引不会包含在返回值中。如果您可以指定异常来自的行,则会有所帮助。对我来说,似乎至少有一个子字符串方法调用使用了错误的索引。