由于某种原因,我的代码的这一部分有一些逻辑(java.lang.ArrayIndexOutOfBoundsException)错误。我希望用户输入任何内容并将其拆分并解析为整数。如果用户未能这样做,请再次询问他们。如果他们输入类似“g5 3 76h 23”的内容,让程序将其接受为 5 3。或者如果我可以让程序拒绝这一点,直到用户只输入 0 到 9 之间的两个由空格分隔的数字,那就没问题了还有。用户还可以选择输入“q”来退出。 但是,每次我运行它时,似乎没有任何内容被分割到新数组中。我收到错误。
/**
* Prompts the user for input
*/
public void promptUser() {
// a Scanner object that uses System.in for input.
Scanner scan = new Scanner(System.in);
// a prompt for the user, asking them for input.
System.out.print("Pick a coordinate [row col] or press [q] to quit: ");
// Get input from the user, checking for errors. If the input is
// correct (e.g., two numbers that in bounds and have not
// already been clicked), then call the click method for desired
// coordinates. If the user wants to quit the game then make sure
// to update the boolean state variable and print out a message.
String input = scan.next();
String del = "[\\s,;\\n\\t]+"; // these are my delimiters
String[] token = input.split(del); // here i will save tokens
int val0 = 11, val1 = 11;
boolean tf = true;
while(tf)
{
if(token[0] == "q")
{
isRunning = false;
System.out.println("Thank you for playing");
}
else
{
try
{
val0 = Integer.parseInt(token[0], 10);
}
catch (NumberFormatException nfe)
{
// invalid data - set to impossible
val0 = 11;
}
try
{
val1 = Integer.parseInt(token[1], 10);
}
catch (NumberFormatException nfe)
{
// invalid data - set to impossible
val1 = 11;
}
}
if( !(((val0 >= 0) && (val0 < rows)) && ((val1 >= 0) && (val1 < cols))) )
{
System.out.println("Input Invalid, pick a coordinate [row col] or press [q] to quit: ");
input = scan.next();
for(int i=0;i<2;i++)
{
token = input.split(del);
}
}
else if(false) //atm
{
}
else
{
tf = false;
}
click(val0, val1);
} //while loop
} // promptUser
最佳答案
您需要验证返回的 token[]
数组的长度,因为可能不会返回“ token ”。即,在没有首先确保它们存在的情况下,您不应尝试访问 token[0]
和 token[1]
。
示例检查:
if(token.length > 1)
关于java - 拆分字符串并将其解析为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327094/