由于某种原因,我的这部分代码中有一些逻辑(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