This is the accept function for my tic tac toe program, so s
is only going to store data in String format and in between 0,0 or 2,2.
I am now using the getNumericValue
function to store the numbers in p
and q
respectively, but during runtime, I get a StringIndexOutOfBounds
exception, when trying to store the value in p
.
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);
}
Hey I finally found the problem in the code. The choice() function accepts a character, but after that when the string is accepted, instead of giving the user the chance to enter the string the machine takes null as the input string automatically(produced when pressing space after the character).
This problem is produced whenever one tries to accept a string or any other data type after CHAR, for example, the input for 's' here after the input 'ch'.
Read input as a string, and extract the first character to consume and discard the subsequent spaces and newlines I also found a way to hack this problem though. :)
import java.io.*;
class tictactoe
{
BufferedReader xy=new BufferedReader(new InputStreamReader(System.in));
void accept()throws IOException
{
System.out.println("Enter your weapon X or O : ");
char ch = xy.readLine().charAt(0); #Ahaaa momemt
System.out.println("Your move:");
String s=xy.readLine();
}
}