i feel dumb for asking this but i have been fighting with this for a day now and i can't seem to get it working.
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
That it keeps updating the Integer I have this now;
int val = 1;
int g = 1;
val = g + val;
But it keeps saying its 2 how come?
Thanks.
I'm guessing you put all of your code in your click handler. Instead, put the variable declaration/initialization in the class level and only your addition code in your click handler. Rough code as follows:
public YourActivity extends Activity {
int val = 1;
int g = 1;
#Override
protected void onCreate (Bundle savedInstanceState) {
... //find button in here
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
val = g + val;
}
});
}
}
Because you keep setting it to 1. Initialize it outside the loop.
int val = 1;
int g = 1;
The next line:
val = g + val;
is therefore equivalent to
val = 1 + 1;
which is equivalent to
val = 2;
Not sure what you would expect here...
int val = 1; int g = 1; val = g + val;
Will always evaluate to 2. Because what happens is you take the value in g which is 1 and the value in val which is 1. This produces the sum of 2. You then take 2 and assign it to the variable val (which previously was initialized to 1).
1+1 will always be 2 (in Integer mathematics)
So my problem is I want to keep adding 1 to and integer and make it go like ;
1+1=2
2+1=3
I'm guessing you want to do something like this, to produce your output a given number of times.
int timesToLoop = 10;
int summedUp = 0;
for (int i=0; i < timesToLoop; i++)
{
summedUp = i + 1;
System.out.println(i + " + " + "1 = " + summedUp);
}
Related
In the databse adapter, I'm trying to create a if (a & b) {select count from sqlite} .. full code as below.. however the cat variable is not recognized (as highlighted?
int samsung = 10;
int iphone = 20
public int getChick() {
int cat = 0;
if (red == 1 & blue == 2) {
int pit = (int) DatabaseUtils.longForQuery(db, "SELECT COUNT(*)
FROM table where one >= " + samsung + " and two >= " + iphone, null);
//////>>>>>> this cat is not recognized by eclipse
int cat = 0 + pit;
}
int dog = cat;
return dog;
}
Thing is, I don't see how it is wrong. If you could please point it out to me. Thanks.
you declare cat in the first line of the method and again inside the if statement. you need to remove the int declaration on the second one
Change
int cat = 0 + pit;
to
cat = 0 + pit;
It looks like you're simply declaring it again when you've already declared it.
My app structure is like, there are 1000 masjids/mosques and each masjid has been given a unique id like 1,2,3,4 ..... 1000 . Now each mosque has seven alarms associated with it , I wish to generate a unique request code number for each alarm so that they don't overlap each other,
Following is the code:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID *(10)) + (namazType);
}
Will this code work?
you can simply concatenate masjidID and namaztype( or specifically namaz ID). This will always return unique.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return Integer.ParseInt(String.valueOf(MasjidID)+""+NamazType)
}
Use Random class:
Try out like this:
//note integer NamazType has range 0 to 5
public int generateRequestCodeForAlarm(int MasjidID, int NamazType)
{
return (MasjidID * (Math.abs(new Random().nextInt()))) + (namazType);
}
It will work for sure.
public int generateRequestCodeForAlarm(int MasjidID,int NamazType )
{
return (MasjidID*(10)) + (NamazType );
}
Output:
Have a look at this
If MasjidID and NamazType are unique, then
Integer.parseInt( MasjidID + "" + NamazType );
would be enough to do the trick!
Example:
Masjid ID = 96, Namaz type = 1, Unique no = 961
MasjidId = 960, Namaz type = 1, Unique no = 9601
MasjidID = 999, Namaz type = 6, Unique no = 9996
I don't find any way in which it would get repeated. However, it is very similar to
(MasjidID * 10) + NamazType
Irrespective of MasjidID and NamazType, if a random number needs to be generated, this can be used.
public class NoRepeatRandom {
private int[] number = null;
private int N = -1;
private int size = 0;
public NoRepeatRandom(int minVal, int maxVal)
{
N = (maxVal - minVal) + 1;
number = new int[N];
int n = minVal;
for(int i = 0; i < N; i++)
number[i] = n++;
size = N;
}
public void Reset() { size = N; }
// Returns -1 if none left
public int GetRandom()
{
if(size <= 0) return -1;
int index = (int) (size * Math.random());
int randNum = number[index];
// Swap current value with current last, so we don't actually
// have to remove anything, and our list still contains everything
// if we want to reset
number[index] = number[size-1];
number[--size] = randNum;
return randNum;
}
}
I have 16 buttons, whose names are "button1", "button2", and so on. Is there a way I can iterate through them using a for loop, by somehow appending the number value upon each iteration? Something like this:
for(int i = 1; i<17; i++ ){
Button b = (Button)findViewById(R.id.buttoni);
I know I can simply initialize each button in my onCreate() method, but I was just curious if I could do it in a way similar to my example code.
Thank you.
You can use getIdentifier :
for(int i = 1; i<17; i++ ){
int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName());
Button b = (Button)findViewById(buttonId);
//Your stuff with the button
}
You can create an array of Button's and use getIdentifier method that allows you to get an identifier by its name.
final int number = 17;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
In case someone is interested how to achive the same result using Java only
The solution above uses Android specific methods (such as getResources, getIdentifier) and can not be used in usual Java, but we can use a reflection and write a method that works like a getIdentifier:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
And then:
final Button[] buttons = new Button[17];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
NOTE:
Instead of optimizing this kind of code you should rethink your layout. If you have 17 buttons on the screen, a ListView is probably the better solution. You can access the items via index and handle onClick events just like with the buttons.
I need help on figuring out why this code is giving me:
Syntax error on token ":", { expected after this token/line
108,109,110(label125,label192,label202 in the beginning)/Java Problem
public void onGPSUpdate(Location paramLocation)
{
if (paramLocation != null)
{
this.sampleCount = (1 + this.sampleCount);
label125: int i;
label192: int j;
label202: int m;
if (paramLocation.hasSpeed())
{
this.speed = (2.23693629D * paramLocation.getSpeed());
this.oldLocation = paramLocation;
this.mAvgSum += this.speed;
this.speedQ.add(Double.valueOf(this.speed));
if (this.speedQ.size() > 300)
this.mAvgSum -= ((Double)this.speedQ.remove()).doubleValue();
if (!this.speedQ.isEmpty())
break label324;
this.mAvg = 0.0D;
if (this.speed <= this.speedThreshold)
break label363;
this.THRESHOLD_STATUS = ("OVER: " + this.speedThreshold + " MPH");
if (!this.smsControlRunning)
{
smsControlOn();
this.smsControlRunning = true;
}
if (!this.blueToothPaired)
break label346;
i = 0;
if (!this.hasBlueTooth)
break label351;
j = 0;
int k = i | j;
if (!this.phoneControlRunning)
break label357;
m = 0;
label218: if ((k & m) != 0)
{
phoneControlOn();
this.phoneControlRunning = true;
}
}
while (true)
{
this.SPEED_STATUS = String.valueOf(this.speed);
this.COUNT_STATUS = (this.sampleCount + " updates");
this.MAVG_STATUS = ("mAvg: " + this.mAvg);
return;
this.speed = getSpeed(this.oldLocation, paramLocation);
break;
label324: this.mAvg = (this.mAvgSum / this.speedQ.size());
break label125;
label346: i = 1;
break label192;
label351: j = 1;
break label202;
label357: m = 1;
break label218;
label363: this.THRESHOLD_STATUS = ("UNDER: " + this.speedThreshold + " MPH");
stopAllServices();
}
}
Toast.makeText(this, "LOCATION NULL", 0).show();
}
This is probably an obvious error but I am relatively new to Android development and using Eclipse. The same code worked fine under a previous version before renaming(refactoring) the application. This was coded by another programmer who worked on the project before me and I think this could be done better using a case or switch statement instead of the break and continue we have. I am getting frustrated with it and would appreciate any advice.
Try using those labels for "real" code lines.
You're using them at variable declarations, so no real point to go.
Use somthing like...
int i;
int j;
int m;
label125: i=0;
label192: j=0;
label202: m=0;
if (paramLocation.hasSpeed())
I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object