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
}
}
Related
Fairly straight forward question. I am trying to get this while loop to iterate only 1 time, to display either chute or ladder. But upon execution it runs through the loop two times. EDIT: I have also have a for loop implemented beforehand and with the same results.
public static String writeLogFile(String filename, int[] gameBoard) {
File fileStream = null;
PrintWriter outputFile = null;
String logFileName = null;
int i = 0;
try {
logFileName = filename.replace(".", "_log.");
fileStream = new File(logFileName);
outputFile = new PrintWriter(fileStream);
while(gameBoard.length > i) {
if(gameBoard[i] > 0) {
System.out.println("Ladder at square " + i);
}
else if(gameBoard[i] < 0) {
System.out.println("Chute at square " + i);
}
++i;
}
}
catch(FileNotFoundException b) {
logFileName = "null";
System.out.println("ERROR! Cannot create log file.");
}
outputFile.close();
return logFileName;
If the length of gameBoard is more than 1, the while-loop is going to continue to execute until it's complete. If you only want it to execute once when finding a ladder or schute then you need to break.
while(gameBoard.length > i) {
if(gameBoard[i] > 0) {
System.out.println("Ladder at square " + i);
break;
} else if(gameBoard[i] < 0) {
System.out.println("Chute at square " + i);
break;
}
++i;
}
It seems that you call the method writeLogFile() twice, because the method itself iterates one once over the complete gameBoard array.
I have instruction to determine if that method returns an exception, and used it in an if switch in the main method. Thank you so much. Now just how to figure out to determine if this method throws an exception.
Then maybe you should not catch the FileNotFoundException within your method, but instead declare it as thrown exception:
public static String writeLogFile(String filename, int[] gameBoard) throws FileNotFoundException {
// ...
}
Then you can catch the exception in your main method.
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();
}
What is the Java equivalent of the while/else in Python? Because it doesn't work in Java. The first chunk was my python code and the second portion is my attempt to translate it into Java. Edit: tring to replicate while-else
while temp.frontIsClear():
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
temp.move()
else:
if temp.nextToABeeper():
temp.pickBeeper()
count += 1
print "The count is ", count
Java Attempt
Robot temp = new Robot();
int count = 0;
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
else
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
}
print ("The count is ", count);
The closest Java equivalent is to explicitly keep track of whether you exited the loop with a break... but you don't actually have a break in your code, so using a while-else was pointless in the first place.
For Java folks (and Python folks) who don't know what Python's while-else does, an else clause on a while loop executes if the loop ends without a break. Another way to think about it is that it executes if the while condition is false, just like with an if statement.
A while-else that actually had a break:
while whatever():
if whatever_else():
break
do_stuff()
else:
finish_up()
could be translated to
boolean noBreak = true;
while (whatever()) {
if (whateverElse()) {
noBreak = false;
break;
}
doStuff();
}
if (noBreak) {
finishUp();
}
Just use one more if statement:
if (temp.nextToABeeper())
// pick beer
} else {
while (temp.frontIsClear()) { /* your code */ }
}
Or:
if (temp.frontIsClear())
while (temp.frontIsClear()) { /* your code */ }
} else if (temp.nextToABeeper()) {
// pick beer
}
If you look at the Java Backus–Naur form Grammar (Syntax Specification), else never follows a while.
Your solution needs to be modified accordingly. You can put the while in an else, that way you handle the if statement.
if temp.nextToBeeper() {
//handle
} else {
while(temp.frontIsClear()) {
//handle
}
}
Try this:
Robot temp = new Robot();
int count = 0;
if (temp.frontIsClear())
{
while (temp.frontIsClear())
{
if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
temp.move();
}
}
else if (temp.nextToABeeper())
{
temp.pickBeeper();
count += 1;
}
print ("The count is ", count);
In Java
if is a conditional statement .
But
while is loop that is iterate again an again and stop itself when falsecondition occurred .
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.
I have a console application in which I would like to put a non-deterministic progress bar on the command line while some heavy computations are done. Currently I simply print out a '.' for each iteration in a while loop similar to the following:
while (continueWork){
doLotsOfWork();
System.out.print('.');
}
which works but I was wondering if anyone had a better/cleverer idea since this can get to be a little bit annoying if there are many iterations through the loop.
Here an example to show a rotating progress bar and the traditional style :
import java.io.*;
public class ConsoleProgressBar {
public static void main(String[] argv) throws Exception{
System.out.println("Rotating progress bar");
ProgressBarRotating pb1 = new ProgressBarRotating();
pb1.start();
int j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb1.showProgress = false;
System.out.println("\nDone " + j);
System.out.println("Traditional progress bar");
ProgressBarTraditional pb2 = new ProgressBarTraditional();
pb2.start();
j = 0;
for (int x =0 ; x < 2000 ; x++){
// do some activities
FileWriter fw = new FileWriter("c:/temp/x.out", true);
fw.write(j++);
fw.close();
}
pb2.showProgress = false;
System.out.println("\nDone " + j);
}
}
class ProgressBarRotating extends Thread {
boolean showProgress = true;
public void run() {
String anim= "|/-\\";
int x = 0;
while (showProgress) {
System.out.print("\r Processing " + anim.charAt(x++ % anim.length()));
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}
class ProgressBarTraditional extends Thread {
boolean showProgress = true;
public void run() {
String anim = "=====================";
int x = 0;
while (showProgress) {
System.out.print("\r Processing "
+ anim.substring(0, x++ % anim.length())
+ " ");
try { Thread.sleep(100); }
catch (Exception e) {};
}
}
}
Try using a carriage return, \r.
In GUI applications the approach is generally a spinning circle or bouncing/cycling progress bar. I remember many console applications using slashes, pipe and hyphen to create a spinning animation:
\ | / -
You could also use a bouncing character in brackets:
[-----*-----]
Of course, as the other answered mentioned, you want to use return to return to the start of the line, then print the progress, overwriting the existing output.
Edit: Many cooler options mentioned by Will in the comments:
Cooler ASCII Spinners?
If you know how much work you have to do and how much is left (or done), you might consider printing out a percent complete bar graph sort of progress bar. Depending on the scope of this project, this could simply be in ascii or you could also consider using graphics.