我正在学习java,所以如果它看起来很基本的话,请耐心等待。我有一个方法,我试图编辑以返回一个'读入'的值 - 我试图返回'移动'。但是,由于代码的设置,返回属于代码块并迫使我返回null。有人可以编辑代码,以便返回“移动”值吗?我已经为此工作了2天而且我无法解决这个问题 - 尝试和捕获似乎导致问题
public Move listenToEngineMove()
{
synchronized(engineReadBuffer)
{
int numRows=engineReadBuffer.size();
if(numRows==0);
for(int kk=0; kk<numRows; kk++)
{
String row=engineReadBuffer.get(kk);
row=row.toLowerCase();
if((row.contains("move "))||(row.contains(" ... ")))
if((!row.contains("illegal"))&&(!row.contains("error")))
try {
String[] tokens=row.replaceAll("\\<.*\\>"," ").split("\\s+");
Move move = new Move(tokens[tokens.length-1]);
jcb.makeAIsMove(move);
System.out.println("thread.... " + row);
}
catch (Exception x) {
System.out.println("Exception! : "+x.getMessage());
}
}
engineReadBuffer.clear();
}
return null;
}
答案 0 :(得分:4)
试试这个:
public Move listenToEngineMove() {
Move move = null;
synchronized (engineReadBuffer) {
int numRows = engineReadBuffer.size();
if (numRows == 0) ; // what on earth is this?
for (int kk = 0; kk < numRows; kk++) {
String row = engineReadBuffer.get(kk);
row = row.toLowerCase();
if ((row.contains("move ")) || (row.contains(" ... ")))
if ((!row.contains("illegal")) && (!row.contains("error")))
try {
String[] tokens = row.replaceAll("\\<.*\\>", " ").split("\\s+");
move = new Move(tokens[tokens.length - 1]);
jcb.makeAIsMove(move);
System.out.println("thread.... " + row);
} catch (Exception x) {
System.out.println("Exception! : " + x.getMessage());
}
}
engineReadBuffer.clear();
}
return move;
}
我建议您替换它:
catch(Exception x){System.out.println("Exception! : "+x.getMessage());}
用这个:
catch(Exception e){
e.printStackTrace(); // Or, better yet, logging with Log4J
}
完整的堆栈跟踪提供的信息比消息更多。
这条线对我来说是个错误。最后的分号看起来不合适。
if (numRows == 0) ; // what on earth is this?
您的代码看起来很糟糕。我发现很难阅读,因为你的缩进和一般代码风格不一致。风格很重要;它使您的代码更易于阅读和理解。采用更好的风格并坚持下去。
答案 1 :(得分:2)
你需要在同步块中移动'Move',将它保持在同步块内是很重要的,以保持线程安全。
public Move listenToEngineMove()
{
synchronized(engineReadBuffer)
{
Move move =null;
int numRows=engineReadBuffer.size();
if(numRows==0);
for(int kk=0; kk<numRows; kk++)
{
String row=engineReadBuffer.get(kk);
row=row.toLowerCase();
if((row.contains("move "))||(row.contains(" ... ")))
if((!row.contains("illegal"))&&(!row.contains("error")))
try {
String[] tokens=row.replaceAll("\\<.*\\>"," ").split("\\s+");
move = new Move(tokens[tokens.length-1]);
System.out.println("thread.... " + row);
}
catch(Exception x){System.out.println("Exception! : "+x.getMessage());}
}
engineReadBuffer.clear();
return move;//this is inside synchronized block
}
}