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();
}
Related
I have this method.
int m = 0;
int a = 0;
#Override
public void animate(long deltaMs){
...
a++;
double valor = destValue * 100f;
if(a%17==0 && valor > 1) {
MySQLAccess sql = new MySQLAccess();
int p = 0;
try {
p = sql.getRandom();
} catch (Exception e) {
}
m++;
if(m == p+1) {
MainFrame mf = new MainFrame();
RandomProvider randomp = new RandomProvider();
QueryPanel qp = new QueryPanel(randomp);
try {
sql.insertScore(valor,sql.getUsuarios(qp.getUsuario()),
sql.getRandom());
} catch (Exception e) {
e.printStackTrace();
}
}
}
repaint();
}
}
This method executes itself multiple times on runtime, and I wanted to keep track of how many times it did, the variable "a" does get added correctly but "m" that is inside the if statement doesn't and I don't know why, I need to know how many times that if statement runs.
Since you want to know how many times the if statement run (and you don’t use debugger), store those times in a variable.
//...
int timesRun = 0;
while( ){
if( ){
timesRun++;
}
}
System.out.println(“Debug: I’d statement run”+timesRun+” times”);
if MySQLAccess sql = new MySQLAccess() throws, m++ will not be reached.
EDIT: closed because it seems that the code below works
I am currently facing the following problem:
I have two two-dimensional arrays, of which the second dimension always has the size 7 (max. index is therefore 6).
Now I need to compare these arrays.
I want to print out if there has been a field added or removed, at any index.
For example:
Array 1:
0|1|2|3
0 |1|2|5
1 |4|4|6
(...)
6 |6|2|8
Array 2
0|1|2|3|4
0 |1|1|2|5
1 |4|4|4|6
(...)
6 |6|7|2|8
As you can see, I have added a column to the second array.
Now I need to print out this column or add it to an array list.
The same has to happen when a column gets removed or changed.
How can I achieve that?
My code so far:
static List<String[]> differences;
static List<String[]> checkForDifferences(String[][] tableOld,String[][] tableNew) {
differences = new ArrayList<String[]>();
if(!Arrays.deepEquals(tableNew,tableOld)) {
for(int hour = 0; hour < tableOld.length;hour++) {
try {
boolean removed = true;
for(int hour2 = 0;hour2 < tableNew.length;hour2++)
if(Arrays.equals(tableOld[hour],tableNew[hour2]))
removed = false;
if(removed)
differences.add(new String[]{"-",tableOld[hour][0], tableOld[hour][1], tableOld[hour][2], tableOld[hour][3], tableOld[hour][4], tableOld[hour][5], tableOld[hour][6]});
} catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
break;
}
}
for (int hour = 0; hour < tableNew.length; hour++) {
try {
boolean added = true;
for (int hour2 = 0; hour2 < tableOld.length; hour2++)
if (Arrays.equals(tableNew[hour], tableOld[hour2]))
added = false;
if (added)
differences.add(new String[]{"+", tableNew[hour][0], tableNew[hour][1], tableNew[hour][2], tableNew[hour][3], tableNew[hour][4], tableNew[hour][5], tableNew[hour][6]});
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
break;
}
}
return differences;
} else {
return null;
}
}
Apparently, my code works. I was just using it wrong.
I am trying to cycle through all parts of a HashMap using a for loop. The problem however is, that inside the body of the for loop, the code is not being fully performed. That is , it is happening only to a certain point and is then stopping.My code is:
public static void printCombination(String arr[], int n, int r)
{
// A temporary array to store all combination one by one
Log.e("ERROR","ATLEAST I'M INSIDE");
String data[]=new String[r];
for(int no = 0;no<arr.length;no++){
boolean decider = true;
if (latest.cart_names.size()>0) {
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
Log.e("ERROR", "ATLEAST I'M INSIDE 1");
String arrayElement = arr[no];
Map<String, Integer> outerMapValue = entry.getValue();
Log.e("ERROR", "ATLEAST I'M INSIDE 2");
if (outerMapValue.containsKey(arrayElement)) {
Log.e("ERROR", "ATLEAST I'M INSIDE 3");
if (outerMapValue.get(arrayElement) != null) {
Log.e("ERROR", "ATLEAST I'M INSIDE 4");
if (outerMapValue.get(arrayElement) > 0) {
return;
}else{
Log.e("ERROR", "ATLEAST I'M INSIDE 5");
decider = false;
}
}
}
}
Log.e("ERROR",Boolean.toString(decider));
Log.e("ERROR",Integer.toString(finalmap.size()));
if (finalmap.size()==0) {
if (decider) {
Log.e("ERROR", "ATLEAST I'M INSIDE 8");
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
Log.e("ERROR", "ATLEAST I'M INSIDE 6");
finalmap.add(rt,arr[no]);
}
}
}else{
if (decider) {
int sum1 = 0;
int sum2 = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2 += latest.cart_names.get(entry.getKey()).get(arr[no]);
}
Log.e("ERROR",Integer.toString(sum1));
Log.e("ERROR",Integer.toString(sum2));
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
Log.e("ERROR", "ATLEAST I'M INSIDE 7");
finalmap.add(arr[no]);
}
}
}
}
}}
It is not logging lines:
Log.e("ERROR",Boolean.toString(decider));
Log.e("ERROR",Integer.toString(finalmap.size()));
This condition is met and the returning/exiting the method...
if (outerMapValue.get(arrayElement) > 0) {
return;
Edit:
as #petey and #Andrew L commented (Thanks for the suggestions (: )
you should consider to take a look to the java best practices and how to use branching control statement
The continue and break statement can be used to skips the current iteration of a for,
while , or do-while loop.
I would guess that it's not logging the lines you list because of the return statement inside the loop. If you want the loop to terminate at that point and still log the lines, you should use break instead.
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.
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
}
}