Variable not adding 1 to itself inside if statement - java

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.

Related

How to know if there is an action on the DB in Java?

I have two applications A and B and I need to modify data in B that comes through a DB from A (check if there is a new record in a specific table).
I have put an infinite loop on B, however I think that is not the best solution.
int i = 0;
for(;;)
{
for(i = 0; i <= 600000;)
{
i++;
}
//Check if there is a new record in a table from app A.
String raw_xml = B.checkDB();
//if there is a new record in a table from app do the
// function doPingTest ()
if (raw_xml!= null)
{
new TestB().doPingTest(raw_xml);
}
i = 0;
}
After doing some tests with other alternatives, this is the best solution:
for(;;)
{
while(true)
{
//sleep one minute
Thread.sleep(60 * 1000);
//Check if there is a new record in the DB
String raw_xml = B.checkDB();
if (raw_xml!= null)
{
new TestB().doPingTest(raw_xml);
}
}
}

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();
}

Assigning an object to a variable with methods in catch block

When I try to compile my code I get error cannot find symbol for .size() and .get(int).
If I move the for loop outside the catch block I get a cannot find symbol error for the
currentUserDiary variable.
getExisitingDiaries() returns a DiaryBook so I thought this would work.
Just wondering if there is something wrong with assigning an Object to a variable this way or if theres something wrong with the rest of my code.
I have to use the catch block because the methods read from a text file.
AccountList aListOb = new AccountList();
try {
aListOb.loadExistingDiaries(myAccountName);
DiaryBook currentUserDiary = new DiaryBook();
currentUserDiary = aListOb.getExistingDiaries(myAccountName);
for (int i = 0; i < currentUserDiary.size(); i++) {
System.out.println(currentUserDiary.get(i));
}
} catch (IOException e) {
}
these methods are in the AccountList class:
public void loadExistingDiaries(String name) throws IOException {
for(int i = 0; i < aList.size(); i++)
{
if (aList.contains(new Account(name, null))) {
aList.get(i).loadExistingDiaries();
break;
}
}
}
public DiaryBook getExistingDiaries(String name) throws IOException {
DiaryBook d = new DiaryBook();
for(int i = 0; i < aList.size(); i++)
{
if (aList.contains(new Account(name, null))) {
aList.get(i).loadExistingDiaries();
d = aList.get(i).getDiaryBook();
break;
}
}
return d;
}
The scope of a variable declared inside a try block is the try block itself, Trying to access it from outside will cause a compilation error, since that variable is not visible.
If you want to use that variable outside the try you need to declare it outside as well.
DiaryBook currentUserDiary = null;
try {
aListOb.loadExistingDiaries(myAccountName);
currentUserDiary = aListOb.getExistingDiaries(myAccountName);
for (int i = 0; i < currentUserDiary.size(); i++) {
System.out.println(currentUserDiary.get(i));
}
} catch (IOException e) {
}
if(currentUserDiary != null){
//Do your business
}
You didnt share the code of DiaryBook. So can't tell if get() and size() are actually declared.
Make sure get() and size() are declared in DiaryBook and are visible(public accessor).
Type cast it to DiaryBook when getting from a Generic List.
And, as suggested by Guillermo Merino, declare the variable outside the try catch block to be able to use it.

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
}
}

Accessing the Android media stream for audio visualization

Basically, I want to make an audio visualizer. I know it's possible, because my phone came with a few live wallpapers that do it. The problem is, I can't seem to figure out how to do this with the Android API.
My app would pick up the currently playing media stream and then depending upon the volume that is playing at that time, it would display more or less bars on the screen.
How can I do this? It looks like I could do something like this using the microphone, but I want to be able to do it for music, podcasts, etc.
It looks like in 2.3 things have changed here, there is permissions now
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
And there is a AudioCapture helper class in the aosp to help the live wallpapers do it properly.
https://android.googlesource.com/platform/packages/wallpapers/MusicVisualization/+/gingerbread-release/src/com/android/musicvis/AudioCapture.java
Edit:
One of the imports in the AOSP doesn't match the public api.
import android.media.audiofx.Visualizer;
it is
import android.media.Visualizer;
if it gives a headache make sure to switch. This is all 2.3 api, it apparently returns a low-resolution audio stream for viz, but not good enough for recording.
The MusicVisualization wallpaper source is available at the AOSP. It basically seems to involve calling MediaPlayer.snoop(), an undocumented method added in Eclair.
Basically what roskit said except with a minor return value modification from
return 0;
to
return Integer.parseInt( (m.invoke(c, outData, kind)).toString() );
In other words:
public static int snoop(short [] outData, int kind){
try {
Class c = MediaPlayer.class;
Method m = c.getMethod("snoop", outData.getClass(), Integer.TYPE);
m.setAccessible(true);
return Integer.parseInt( (m.invoke(c, outData, kind)).toString() );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 1;
}
}
A slightly faster snoop() would be to call Class.getMethod() once, and then to use a custom parseInt() instead of Integer.parseInt()...
private static Method mSnoop;
//..(http://nadeausoftware.com/node/97)..
private static int customParseInt( final String s )
{
// Check for a sign.
int num = 0;
int sign = -1;
final int len = s.length( );
final char ch = s.charAt( 0 );
if ( ch == '-' )
sign = 1;
else
num = '0' - ch;
// Build the number.
int i = 1;
while ( i < len )
num = num*10 + '0' - s.charAt( i++ );
return sign * num;
}
private static int snoop(short [] outData, int kind)
{
if ( mSnoop != null )
{
try
{
return customParseInt( (mSnoop.invoke( MediaPlayer.class , outData, kind)).toString() );
}
catch ( Exception e )
{
Log.e( TAG, "Failed to MediaPlayer.snoop()!", e );
return 1;
}
}
else
{
try {
Class c = MediaPlayer.class;
Method m = c.getMethod("snoop", outData.getClass(), Integer.TYPE);
m.setAccessible(true);
mSnoop = m;
return customParseInt( (m.invoke(c, outData, kind)).toString() );
}
catch (Exception e)
{
Log.e( TAG, "Failed to MediaPlayer.snoop()!", e );
return 1;
}
}
}
This is how I did it from my application:
protected short [] mAudioData = new short[1024];
Then in the loop:
int res = snoop(mAudioData, 0);
And here is the function itself:
public static int snoop(short [] outData, int kind){
try {
Class c = MediaPlayer.class;
Method m = c.getMethod("snoop", outData.getClass(), Integer.TYPE);
m.setAccessible(true);
m.invoke(c, outData, kind);
return 0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 1;
}
}
Look at http://code.google.com/p/moonblink/wiki/Tricorder for an example.

Categories

Resources