Minesweeper - Online Judge "Wrong answer" although it works on Netbeans - java

I was trying to submit Minesweeper problem on UVa (http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1130)
Sample input:
4 4
*...
....
.*..
....
Sample output:
*100
2210
1*10
1110
I have developed the code on NetBeans. I have tested it and it was working fine, but when I try to submit it on UVa it result a Wrong Answer for the submition.
I have two questions:
1)What is the problem in my code?
2)What should I use and what shouldn`t I use while coding for UVa?
-If there is a different standard I should follow, please advice
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
String REGEX_WHITESPACE = "\\s+";
String cleanLine = line.trim().replaceAll(REGEX_WHITESPACE, " ");
String[] numChar = cleanLine.split(REGEX_WHITESPACE);
int n = new Integer(numChar[0]).intValue();
int m = new Integer(numChar[1]).intValue();
char[][] mine = new char[n][m];
char[] curLine;
for(int i=0;i<n;i++){
line=reader.readLine();
cleanLine = line.trim().replaceAll(REGEX_WHITESPACE, " ");
curLine = cleanLine.toCharArray();
if(curLine.length==m){
mine[i]=curLine;
}
}
int starsCount=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(mine[i][j]=='*'){
System.out.print('*');
}
else{
try {
if (mine[i][j - 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i][j + 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i-1][j] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i+1][j] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i-1][j - 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i-1][j + 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i+1][j - 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
try {
if (mine[i+1][j + 1] == '*') {
starsCount++;
}
} catch (Exception e) {
}
if(j==m-1){
System.out.println(starsCount);
}
else{
System.out.print(starsCount);
}
starsCount=0;
}
}
}
}
}

Here is one thing you can look at.
When you know your program has to give output that looks exactly like a sample, e.g. in your case
*100
2210
1*10
1110
You should check for hidden whitespace - such as spaces, tabs, new lines (which can be \r, \n or \r\n format). In particular, common gotchas are:
-Is there a line break after the last line, or not?
-Does it matter if your line breaks are \r, \n or \r\n?
-If you have extra spaces anywhere, or a line break before you begin the output, does it consider the sample to not match it?
-If there are tabs or lots of spaces, does using tabs instead of spaces or vice versa make the sample not considered to match?
I see one potential gotcha in your code.
If the right edge of a row is a mine, it will print('*') rather than println('*'). To solve this, do println() irregardless of what was in the cell if it's on the right of a row - don't have logic to print OR println content, just println() with no arguments on its own.
EDIT: And as Charlie mentions in the comments to the original question, you have to code your program to handle more than one field and to print Field #num: before each field.
Meaning instead of putting all your code in main, you should put the code that creates and solves one field into its own method and call that from main while there is still input to read.

Related

concurrent run using ListBlockingQueue thread is getting blocked for some reason

currently, I'm working on a Projekt where I have to make a simple program using Threads and BlockingQueue :
The program is Caesar encoding why the LinkedBlockingQueue well because it's an assignment :).
The Program shall read the letters from the console (including the Carriage return and the line feed char(10) char(13)) which will act as a flag to identify where the not-encoded letters end!.
so the queue would look something like this (assuming the shift factor is 3):
['a'->'a'->'a'->'13'->'d'->'d'->'d']
then while encoding the letter that is being read will get written in the encode queue and removed from the letters queue.
so what I did is the following:
CODE:
import java.io.*;
import java.util.concurrent.*;
public class Caesar {
private final static int CR = 13,LF=10, SHIFT_FACTOR=3, OFFSET=23;
public static void main(String[] args) throws InterruptedException {
var br = new BufferedReader(new InputStreamReader(System.in));
var letters = new LinkedBlockingQueue<Character>();
var encoded = new LinkedBlockingQueue<Character>();
var done = new LinkedBlockingQueue<Boolean>();
Thread t1=new Thread(()-> takeInput(letters,br));
Thread t2=new Thread(()->encode(letters,encoded));
Thread t3=new Thread(()-> send(encoded,done));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println(done.take());
}
private static void takeInput(BlockingQueue<Character>letters, BufferedReader br ) {
System.out.println("Enter your input!.");
int temp;
try {
while((temp=br.read())!=-1) {
letters.put((char) temp);
System.out.println("added "+ temp+ " and letters queue is "+letters);
if (temp == CR || temp == LF){
break;
}
}
}catch (IOException | InterruptedException e){ e.printStackTrace(); }
finally {
try {
br.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
public static void encode(BlockingQueue<Character>letters, BlockingQueue<Character>encoded) {
try {
char tempLetter;
while(!letters.isEmpty()){//dont know why its not going in here!!!! BLOCKED HERE debugger dont want to get in here!
System.out.println("inside encode");
tempLetter=letters.take();
if (tempLetter == CR ||tempLetter ==LF){
encoded.put(tempLetter);
break;
}else if (tempLetter == ' ' || tempLetter == '.') {
encoded.put(tempLetter);
}else if (cap(tempLetter) < 'X') {
encoded.put((char)(tempLetter+SHIFT_FACTOR));/
}else{
encoded.put((char)(tempLetter - OFFSET));
}
}
}catch (InterruptedException e) { e.printStackTrace(); }
}
private static Character cap(Character temp) {
return temp >= 'a' ? Character.toUpperCase(temp):temp;/
}
private static void send( BlockingQueue<Character> encoded, BlockingQueue<Boolean> done){
try {
char temp=encoded.take();
while (!encoded.isEmpty()){
System.out.println("stuck in encode!");
if(temp==CR || temp==LF)
break;
System.out.print(temp);
temp=encoded.take();
}
done.put(true);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Desired OUTPUT
Enter your input!.
aaaa
started encoding
the encoded elements are : -> dddd
The output I'm getting: !
Enter your input!.
aaa
added 97 and letters queue is [a]
added 97 and letters queue is [a, a]
added 97 and letters queue is [a, a, a]
added 10 and letters queue is [a, a, a,
]
(the program is on hold without and doesn't want to enter the while loop in the encrypt!!!!)
The prof gave us a GO code to use it as Reference to be able to realize the functions :
here is a link to the go code on pastebin
feel free to suggest anything :)
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
You start a thread, then wait for it to finish before starting the next.
Put all the joins after the starts:
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
The solution
Mainly, I had to correct the loop condition and use each of take(), put() , offer() correctly.
plus, benefiting from the advice of the user #Andy Turner of not using Iterators nor enhanced for loops.
Further reference for learning the LinkedBlockingQueue:
LinkedBlockingQueue.html#iterator()
Interface BlockingQueue Oracle
Java BlockingQueue tutorials jenkov
GeekForGeek BlockingQueue Interface in Java
the methods look like this now:
private static void encode(BlockingQueue<Character>letters,BlockingQueue<Character> encoded) {
System.out.println("started encoding");
try {
char toEncode;
while (true) {
toEncode=letters.take();
if (toEncode == ' ' || toEncode == '.'){
encoded.offer(toEncode);
}else if (toEncode == CR ||toEncode ==LF){
encoded.offer(toEncode);
break;//reached our flag!.
}else if (cap(toEncode) < 'X') {
encoded.offer((char)(toEncode+SHIFT_FACTOR));
}else{
encoded.offer((char)(toEncode - OFFSET));
}
}
} catch (InterruptedException e) { e.printStackTrace(); }
}
private static void send( BlockingQueue<Character> encoded, BlockingQueue<Boolean> done){
try {
char temp;
while(true){
temp=encoded.take();
if (temp==CR || temp==LF)
break;
System.out.print(temp);
}
System.out.println();
done.offer(true);//no need to use put() though.
} catch (InterruptedException e) { e.printStackTrace(); }
}

Unable to write values into excel using multiple workbook.write methods

The below code is working without any runtime error if I call the owb.write(fileOut) and fileOut.close() method only once at at the ending (commented as write and close positioning) but the problem here is that the first value to be set when k=1, is not being printed in the workbook. It works fine when the iteration is in other columns and k=1.Only the first iteration is not being printed. Rest of the values are being set correctly.
I tried using multiple workbook.write() method. If you look at the below code, commented as [1], I had to invoke owb.write(fileOut) separately in the if condition(commented as if condition[1]) and else condition(commented as else condition [2]) because as I said, first value was not getting set in the workbook. I am getting the following runtime error while trying to execute the code in this scenario: Fail to save: an error occurs while saving the package : The part /docProps/app.xml fail to be saved in the stream with marshaller org.apache.poi.openxml4j.opc.internal.marshallers.DefaultMarshaller#3740f768
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty()) //If condition[i]
{
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut); //[1]
}
else //else condition [1]
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
rowHead = sheet.createRow((short)k);
rowHead.createCell(i).setCellValue(value1);
owb.write(fileOut);
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}
//write and close positioning
fileOut.close();
I tried debugging and found that the createRow() method deletes the values previously created if called again on the same row.
To elaborate this, suppose the sheet.createRow() sets the value of a cell in the first iteration, and when it finishes its iteration in the j for loop, the cFilledPositions list is cleared and while it comes back after going to the main loop, 'cFilledPositionswill be empty and the integerkwill again be initialized to1. This is whencreateRow(k)` which is 1 is called again. This would flush out the previously existing values in the 1st row. I am trying to figure out a work around for this and will edit my answer with the solution if I my code works.
Below was the work around. I checked if the row is empty. The createRow function is called only when the row is empty. I have added the comments for the new code.
for(int i=0;i<noOfCols1;i++)
{
for(int j=1;j<=noOfRows1;j++)
{
value1 = formatter.formatCellValue(sheet1.getRow(j).getCell(i));
for(int m=1;m<=noOfRows2;m++)
{
value2 = formatter.formatCellValue(sheet2.getRow(m).getCell(i));
value1= value1.trim();
value2=value2.trim();
int value2Position = sheet2.getRow(m).getCell(i).getRowIndex();
if(!positions.contains(value2Position))
{
if(value1.contentEquals(value2))
{
positions.add(value2Position);
matched = true;
}
else{
matched = false;
}
}
if(matched==true)
{
break;
}
}
if(matched == false)
{
int k=1;
if(cFilledPositions.isEmpty())
{
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e){
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
else
{
int l = cFilledPositions.size()-1;
k = cFilledPositions.get(l)+1;
try{
isEmpty = checkIfRowIsEmpty(sheet,k,formatter);
if(isEmpty)
{
rowHead = sheet.createRow(k);
}
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e)
{
try{
rowHead = sheet.createRow(k);
rowHead.createCell(i).setCellValue(value1);
}
catch (Exception e1){
}
}
}
cFilledPositions.add(k);
}
matched = false;
}
cFilledPositions.clear();
positions.clear();
}

Retrieving Unknown Value using Jsoup

I'm attempting to pull the 'Total Cash Flow From Operating Activities' figure from Yahoo Finance. The variable "s" can be any symbol in the SP500. For the most part, the desired output occurs. However, in some cases, like for AAPL, I can't figure out what it's printing or where it came from.
If "s" is A, the output is 711000000. Correct.
If "s" is AA, the output is 1674000000. Correct.
However, if "s" is AAPL, the output is -416542144. No clue where that comes from.
public class CashFlowStatement {
String cashFromOperatingActivities = "Total Cash Flow From Operating Activities";
public CashFlowStatement(String s) {
String cashFlowStatementURL = ("https://finance.yahoo.com/q/cf?s="+s+"+Cash+Flow&annual");
String cashFlowStatementTableName = "table.yfnc_tabledata1";
boolean foundLine = false;
String line;
int line2;
try {
Document doc = Jsoup.connect(cashFlowStatementURL).get();
for (Element table : doc.select(cashFlowStatementTableName)) {
for (Element row : table.select("tr")) {
if(foundLine == false) {
Elements tds = row.select("td");
for( int j = 0; j < tds.size() - 1; j++) {
if(tds.get(j).text().equals(cashFromOperatingActivities)) {
line = tds.get(j+1).text().replaceAll(",","");
line = line.substring(0,(line.length())-2);
line2 = Integer.parseInt(line)*1000;
System.out.println(line2);
foundLine = true;
}
}
}
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
catch (NumberFormatException ex) {
ex.printStackTrace();
}
}
}
You have an OVERFLOW! The value from the table is 59,713,000. When you multiply it by 1000 - line2 = Integer.parseInt(line)*1000; you get a number which is greater than MAXINT, thus the negative value. Try use long instead int for line2.

Exception organization assistance?

I had some success with this site, and I hope I find more excellent programmers to assist me.
So I am at my wit's end with this code. I am very new to programming, especially exceptions. I have looked very hard through my course material and sought help, but I have been quite unsuccessful. I am trying to create an improved parser that will override another parser. It reads a .txt file with student information of it including an ID, a name, a grade, and an optional email address and optional comment as tokens in a String separated by commas. The override checks for errors in each token and throws an exception called ParserException. The exception will check the code and then return an error message if the error is unfixable.
For example, if a student puts in an AB for the grade, the exception will flag and check if the input is a valid grade (which it is) and then return, if it is not, then it will throw a ParserException, in this case
throw new ParserException(ParserException.GRADE_INVALID_GRADE,lineIndex);
This shows that the does not work and sends out a message GRADE_INVALID on the line indexLine
I have a list of what I need to have as an output:
Any violation of the file format specified in the Input File Format Description section above should result in an ParcerException with an appropriate message
Duplicate IDs are not allowed
Grade values must be a float (92.0) or a letter grade and not an integer
I have all the code to correct and check for errors, but I cannot figure out how to get the try-catch to work. Here's is the override code:
#Override
public ParserResult parseLine(int lineIndex) {
String[] tokens = lines.get(lineIndex).split(",");
ArrayList<Integer> idList = new ArrayList<Integer>();
Integer studentId;
String name;
String grade;
String email;
String comments;
boolean isFloat;
float gradeFinal;
String editName;
studentId = new Integer(tokens[0]);
ParserResult result;
try{
return super.parseLine(lineIndex);
}
catch(ParserException e){
// Check reasonable number of tokens
if(tokens.length >= 3 && tokens.length <= 5){
name = tokens[1];
grade = tokens[2];
// Check the student ID
if(idList.contains(studentId)){
throw new ParserException(ParserException.DUPLICATE_ID, lineIndex);
}else{
idList.add(studentId);
}
// Check the grade
if(grade.trim().equalsIgnoreCase("A")){
gradeFinal = gradeA;
}else if(grade.trim().equalsIgnoreCase("AB")){
gradeFinal = gradeAB;
}else if(grade.trim().equalsIgnoreCase("B")){
gradeFinal = gradeB;
}else if(grade.trim().equalsIgnoreCase("BC")){
gradeFinal = gradeBC;
}else if(grade.trim().equalsIgnoreCase("C")){
gradeFinal = gradeC;
}else if(grade.trim().equalsIgnoreCase("CD")){
gradeFinal = gradeCD;
}else if(grade.trim().equalsIgnoreCase("D")){
gradeFinal = gradeD;
}else if(grade.trim().equalsIgnoreCase("F")){
gradeFinal = gradeF;
}else{
try{
Integer.parseInt(grade);
isFloat = false;
}
catch(Exception fl) {
isFloat = true;
}
if(isFloat){
if((Float.parseFloat(grade) < 100f) && (Float.parseFloat(grade) >= 0f)){
gradeFinal = Float.parseFloat(grade);
}else{
throw new ParserException(ParserException.GRADE_INVALID_GRADE,lineIndex);
}
}else{
throw new ParserException(ParserException.GRADE_INTEGER_VALUE,lineIndex);
}
}
// Check the name
if(name.split(" ").length > 3){
throw new ParserException(ParserException.UNKNOWN, lineIndex);
}else{
editName = name.trim().split(" ")[0];
}
result = new ParserResult(studentId, editName, gradeFinal);
// Checks the email
if(tokens.length >= 4){
email = tokens[3];
// Check for at sign
if(!email.contains("#")){
throw new ParserException(ParserException.UNKNOWN, lineIndex);
}
int count = 0;
// Counts number of # symbols
for(int i=0; i<email.length(); i++){
if(email.indexOf(i) == '#'){
count++;
}
}
if(count > 1){
throw new ParserException(ParserException.EMAIL_MULTIPLE_AT,lineIndex);
}
if(email.split(".").length == 2){
if(!(email.trim().split(".")[1].contains(".edu")) && !(email.trim().split(".")[1].contains(".com"))){
throw new ParserException(ParserException.EMAIL_NOT_EDU_OR_COM,lineIndex);
}else{
result.setEmail(email);
}
}
// Checks if email contains .com or .edu
// Checks the comments
if(tokens.length == 5){
comments = tokens[4];
result.setComment(comments);
}
}
return result;
}
}
// TODO Call Parser's parseLine() here to attempt to parse, catch any exceptions
return null;
}
The original parseLine that is overridden, but still used is:
public ParserResult parseLine(int lineIndex) {
String[] tokens = lines.get(lineIndex).split(",");
ParserResult result = new ParserResult(Integer.parseInt(tokens[0]),
tokens[1], Float.parseFloat(tokens[2]));
result.setEmail(tokens[3]);
return result;
}
Here is the main() file:
public static void main(String[] args){
// TODO Change the line below to use ImprovedParser
Parser parser = null;
try {
parser = new ImprovedParser(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.exit(-1);
}
List<ParserResult> results = parser.parse();
int count = results.size();
double sum = 0.0;
for (ParserResult result : results) {
sum += result.getGrade();
}
System.out.println("Number of valid input lines: " + results.size());
System.out.println("Number of invalid input lines: "
+ (parser.getLineCount() - results.size()));
System.out.println("Average grade: " + sum / count);
for (ParserResult result : results) {
System.out.println(result);
}
}
Lastly, here is the .txt file that is being read:
# student_id,name,grade,email
1234,Bob,92.0,bob#test.edu
4321,Alice,95.0,alice#test.edu
1111,Eve,80.0,eve#test.edu
1121,Barry,85.0,barrytest.edu
1131,Harry,86.0,h#rry#test.edu
1121,Larry,87.0,larry#test.edu
1141,Jim Song,88.0,jim#song.edu
1151,Jerry,77.0,jerry#test.net
1161,James,65.0,james#test.com
The last six inputs should cause exceptions, but I can't figure out how to organize it to work. The code ignores the line with # symbol.
Here is a sample successful output:
Number of valid input lines: 3
Number of invalid input lines: 0
Average grade: 89.0
1234, 92.0, Bob, bob#test.edu,
4321, 95.0, Alice, alice#test.edu,
1111, 80.0, Eve, eve#test.edu,
The major changes should be in the orverride method
Please help if you can, I sit at my desk still pondering possibilities, and your help will be most-appreciated.
Assuming ParseException has an error field being an int and someMethod() that throws ParseException:
try {
someMethod();
} catch (final ParseExeption ex) {
if (ex.getError() == ParseException.SOME_ERROR) {
// do something
} else if (ex.getError() == ParseException.OTHER_ERROR) {
// do something else
}
}
Note that it's usually better to use specific exceptions for specific error, something like SomeErrorParseException, OtherErrorParseException, ... (those can extends ParseException if you want) and try-catch like this:
try {
someMethod();
} catch (final SomeErrorParseException ex) {
// do something
} catch (final OtherErrorParseException ex) {
// do something else
}
Some reading: http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html
It seems that there is no code to actually cause the catch clause in the first place. Try adding a throw new ParserException(STUFF_HERE); when an error has been detected while reading the file.

Java - add a return statement

I am learning java so bear with me on this if it seems basic. I have a method which I am trying to edit to return a value which is 'read in' - I am trying to return 'move'. However, due to the setup of the code the return falls outside the code block and forces me to return a null. Can someone edit the code so that it returns the 'move' value? I have been working on this for 2 days and I can't work it out - the try and catch seem to be causing the problem
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;
}
Try this:
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;
}
I'd recommend that you replace this:
catch(Exception x){System.out.println("Exception! : "+x.getMessage());}
with this:
catch(Exception e){
e.printStackTrace(); // Or, better yet, logging with Log4J
}
The complete stack trace gives more info than the message.
This line looks like a mistake to me. The semi-colon at the end looks out of place.
if (numRows == 0) ; // what on earth is this?
Your code looks awful. I find it hard to read, because you aren't consistent with your indentation and general code style. Style matters; it makes your code easier to read and understand. Adopt a better style and stick with it.
You will need to move 'Move' just inside synchronized block, It is important to keep it inside synchronized block to stay thread safe.
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
}
}

Categories

Resources