使用字符时的java StringIndexOutOfBoundsException。getNumericValue
这是我的tic-tac-toe程序的accept函数,因此s
只将数据存储为字符串格式,并在0,0或2,2之间
我现在使用getNumericValue
函数分别将数字存储在p
和q
中,但是在运行时,当我尝试将值存储在p
中时,会出现StringIndexOutOfBounds
异常
The problem is happening only when choice() function to decide x or O is called before accept() else it's running fine. What is the problem with the choice() funtion?
void accept()throws IOException
{
System.out.println("Your move:");
String s=xy.readLine();
int p = (Character.getNumericValue(s.charAt(0)))-1;
int q = Character.getNumericValue(s.charAt(2))-1;
if(ar[p][q]==0)
ar[p][q]=1;
else
{
System.out.println("You can't capture a location that has already been captured!");
accept();
}
}
void choice() throws IOException
{
System.out.println("Welcome to tictactoe");
System.out.print("Enter your weapon X or O : ");
chp = Character.toUpperCase((char)xy.read());
if (chp=='X')
chc='O';
else
chc = 'X';
System.out.println("kkbot chose: "+ chc);
}
# 1 楼答案
你的问题是:
这是我的tic-tac-toe程序的accept函数,因此s只以0,0或2,2之间的格式存储数据
但您的代码会:
用户可以输入他想要的任何内容。readLine()中的任何内容都不会阻止他添加空字符串或过长字符串
在使用该字符串执行任何操作之前,必须验证该字符串是否具有假定的长度;例如:
除此之外:请为变量使用real名称。s、 xy,p,q。。。不要告诉读者这些变量的用途。是的,你在打字时节省了一点时间;在以后阅读源代码时,您将花费10倍的时间;而且,你也极大地增加了那些丑陋的单字符名字出现愚蠢拼写错误的可能性
# 2 楼答案
如果您只是试图在两个独立的
int
变量中存储像0,0
或1,1
这样的值,那么这应该是一个简单的过程。不过,您应该对错误输入采取预防措施。 因此,您的accept()
方法应该是这样的:正如@GhostCat正确地提到的,您应该为变量使用专有名称。这提高了代码的可读性
# 3 楼答案
嘿,我终于在代码中找到了问题。 choice()函数接受一个字符,但在接受该字符串之后,当用户没有机会输入该字符串时,机器会自动将null作为输入字符串(在字符后按空格键时生成)
问题
溶液