Android- method is permanently changing the value of variable - android

I have this method which I dont understand.
2 global variables which are important for this questions:
-mNextButton;
-mCurrentIndex;
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
int questionID = nameOfArray[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
});
how is it possible that mCurrentIndex is increased permanently every time user clicks mNextButton?

Try to be more specific. What do you really what to know?
In your code you setup a callback, which will be called, when user press the button. Inside that code you updating your "global" variables (since java has no global variables, I will assume you mean class field variable inside activity)
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
this will update mCurrentIndex exactly as specific - it increase the index for one, and fold it, when the value increase more than mQuestionBank.length. % is a standard modulo operator.
For gaining more understanding check out your mQuestionBank.length parameter or write a better question. Good luck.

For solving this you need to set one local variable. So in your onClick method:-
int mCIndex = mCurrentIndex;
mCIndex = (mCIndex + 1) % mQuestionBank.length;
int questionID = nameOfArray[mCIndex].getQuestion();
mQuestionTextView.setText(question
);
Thats it

The value of mCurrentIndex is set to the value of
(mCurrentIndex+1) % mQuestionBank.length
with every click on mNextButton.
This value is depending on the mCurrentIndex and the length of mQuestionBank. To explain the operation, take a look at the modulo operator:
https://en.m.wikipedia.org/wiki/Modulo_operation
To cut it short:
If mCurrentIndex for example has a value of 4, it's incremented by 1 and you get 5.
Now, it's depending on the length of your mQuestionBank. If it's 2000 it will have 0-1999 residual classes. Every number that you modulo by 2000 will fall into one of these classes.
So if you do the operation 0 mod 2000 equals 0, because 0 divided by 2000 has no remainder.
1 mod 2000 is 1 because 1 divided by 2000 is 0 with a remainder of 1. And 5 mod 2000 will be equal to 5.
In your case: mCurrentIndex will increase with every click until
mCurrentIndex+1 = mQuestionBank.lenght
because then it will start with 0 again. Since, in this example, 2000 mod 2000 is 1 with no remainder.

Related

How to print specific numbers from a for loop using Kotlin

So I am fairly new to Kotlin and I need to generate specific numbers from a for loop of 1 to 13.
For the first output I need only odd numbers
For the second output I need numbers 2, 5, 8, 11, 14, 19 and 20 from a for loop of 0 to 20
For starters I can print an entire list using:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 1..13){
println(i)
}
}
}
But that's it. What do I need to print the other required outputs?
Once you know how to write a for loop that prints every number, the question becomes how to identify a number that you "should" print from a number that you should not.
Your first sequence is all odd numbers, so #DipankarBaghel's answer covers that. Your second sequence seems to be all numbers for which the remainder when dividing by 3 is 2. (Except 19; did you mean 17 for that one?)
You can use the same operator in this case, but instead of checking for 0 (or for != 0) you can check that the remainder is 2:
for (i in 0..20) {
if (i % 3 == 2) {
println(i)
}
}
The key concept here is that of %, the remainder operator (sometimes called the modulo operator). The result of x % y will be the remainder when x is divided by y. Odd numbers have a remainder of 1 when divided by 2, so i % 2 == 1 will be true only for (positive) odd numbers.
To check even you need to do i%2==0 and for odd just check i%2!=0.
for (i in 1..13){
if(i%2!=0){
println("odd number "+i);
}
if(i%2==0){
println("even number "+i);
}
}
Hope this will help you.
To generate Odd numbers:
for (i in 1..13) {
if(i % 2 == 1 ){
println(i + ", ");
}
}
To Generate 2, 5, 8, 11, 14, 19 and 20:
for (i in 0..20) {
if (i % 3 == 2) {
println(i + ", ");
}
}

Java long is calculated wrongly

Consider this piece of code:
// calculate age of dog
long interval = 1000*60*60*24*30;
int ageInWeeks = Weeks.weeksBetween(geburtsDatumDateTime, nowDateTime).getWeeks();
if (ageInWeeks < 20){
// wöchentlich
interval = 1000*60*60*24*7;
} else if (ageInWeeks >= 20 && ageInWeeks < 52){
// 2-wöchentlich
interval = 1000*60*60*24*14;
} else if (ageInWeeks >= 52){
// monatlich
interval = 1000*60*60*24*30;
}
The debugger shows, that in case of ageInWeeks >= 52 the interval is: -1702967296, but it should be: 2592000000
The minus sign suggests some kind of overflow error.
However the maximum value of a long in Java is 2E63-1 which is: 9.2233E18
What I am missing here? Is an Android maximum value for a long smaller?
You're computing 32-bit signed ints, the computation overflows, and then you assign the result to a long.
Do your calculation in 64 bits by making one of the operands a long. For example, add L to one of the operands to make it a long literal:
interval = 1000L*60*60*24*30;
As laalto said, adding a 'L' should make it work.
However, for avoiding these kind of errors in the future, you could use the TimeUnit class (available in Android SDK):
long interval = TimeUnit.DAYS.toMillis(30);

Trying to only do math functions on edittexts users have entered information in on android

I have a 10-field average lap calculator. However, in testing, someone said they normally only run X laps in practice, vs. 10 (let's say 7).
I think I could use an if statement, but there'd be at least 10 of them and a bunch of clumsy code, and I'm not sure on arrays/switch statements exactly. I think all of those might be possible, but my low level of experience has yet to fully comprehend these useful tools.
CURRENT CODE:
double tenLapAvgVar = ((lap1Var + lap2Var + lap3Var + lap4Var + lap5Var + lap6Var + lap7Var + lap8Var + lap9Var + lap10Var) / 10);
So essentially, if someone leaves a field or fields blank, I want to calculate the average based on the populated fields, not 10 (if they leave 3 fields blank, calculate based on 7, for instance). Any help you guys could provide would be much appreciated, thanks!
You could have an ArrayList<EditText> object and a method which iterates over it and adds up the values. Something like:
public double getLapAverage()
{
int noOfCompletedLaps = 0;
double lapAve = 0;
double lapsTotal = 0;
for(EditText text : textBoxes)
{
if(text.getText().toString().length() > 0)
{
//psuedo code, and assuming text is numerical
lapsTotal += Double.parse(text.getText().toString());
noOfCompletedLaps++;
}
}
if( noOfCompletedLaps > 0)
{
lapAve = lapsTotal / noOfCompletedLaps;
}
return lapAve;
}
Maybe it would be better if you used an array instead of 10 different variables.
Then you can use a for statement and initialize them to 0, afterwords let the user fill the array and count how many are not zero.
Finally sum up all the array and divide by the count you previously calculated.

Developing a simple memory game

I'm kinda new to Android, now I'm developing a very simple game, the logic is described as following: The user sees a 10-digit value after pressing a "Ready" Button. After 5 seconds, the value changes to
* * * * * * * and the user has to enter it in a text field (type "number") below. Under that text field there are 2 Buttons: "Check" and "Give a hint". The check Button compares the user value to original value and changes a TextView according to the result("Correct"/"Incorrect"). The hint Button should show 3 random digits in the original value.
I have some questions on that small application:
I'm not sure which type I have to use to show the original value to the user: a
TextView, a text field or something else?
How do I force the app to show 3 random digits from the original value in the case
when user presses the hint Button?
Any help is appreciated.
1). I'm not sure which type I have to use to show the original value to the user: a TextView, a text field or something else?
For this TextView will do.
2). How do I force the app to show 3 random digits from the original value in the case when user presses the hint button?
Hopefully you are using int for storing 10 digit value (original value)
Make an array of int having size 10
int[] digits = new int[10];
Use for loop to separate all 10 digits from the 10 digit number.
int number = 1234567891
for(int i = 0; i < 10; i++){
digits[i] = number % 2;
number = number / 10;
}
This will give you array of 10 int values
Make object of java.util.Random class and fetch random values from 0-9
Random r = new Random();
int pos1 = r.nextInt(9);
nextInt(int n) returns a pseudo-random uniformly distributed int in the half-open range [0, n).
These values are positions from which you are going to retrieve digit from array
So this will give you random position between 0 and 9
Just make sure that each time you generate random value from Random, it should not be equal to previously generated values e.g. if you are generating random position for second digit you should check that it should be equal to first
you can show all 3 digits(fetched from 3 randomly generated positions) in TextView as a hint
Hope this will solve your problem
Edited Part
Set visibility of Textview to View.GONE
something like this
private TextView tv;
tv = (TextView)findViewById(R.id.textView01);
tv.setVisibility(View.GONE);
Button btn = (Button)findViewById(R.id.button01);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View view){
tv.setVisibility(View.VISIBLE);
}
});

Determining even/odd numbers (integers)?

I feel stupid asking such a simple question, but is there an easy way to determine whether an Integer is even or odd?
if ((n % 2) == 0) {
// number is even
}
else {
// number is odd
}
It's not android specific, but a standard function would be:
boolean isOdd( int val ) { return (val & 0x01) != 0; }
Many compilers convert modulo (%) operations to their bitwise counterpart automatically, but this method is also compatible with older compilers.
You can use modular division (technically in Java it acts as a strict remainder operator; the link has more discussion):
if ( ( n % 2 ) == 0 ) {
//Is even
} else {
//Is odd
}
If you do a bitwise-and with 1, you can detect whether the least significant bit is 1. If it is, the number is odd, otherwise even.
In C-ish languages, bool odd = mynum & 1;
This is faster (performance-wise) than mod, if that's a concern.
When somehow % as an operator doesn't exist, you can use the AND operator:
oddness = (n & 1) ? 'odd' : 'even'
Similar to others, but here's how I did it.
boolean isEven = i %2 ==0;

Categories

Resources