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;
Related
This is my goal : user click on minus button the amount decrease by one and there is a if statement to not allow the amount go lower than 0 .
This is my Code :
var number = 0
view.text_amount.visibility = View.GONE
view.plus_btn.setOnClickListener {
if (number == 5) {
Toast.makeText(
requireContext(),
"Limit in order",
Toast.LENGTH_SHORT
).show()
} else {
view.text_amount.visibility = View.VISIBLE
number++
view.text_amount.text = number.toString()
}
}
view.minus_btn.setOnClickListener {
if (number <= 0) {
view.text_amount.visibility = View.GONE
} else {
number--
view.text_amount.text = number.toString()
}
}
there is problem with code : I don't want the amount be visible after getting to 0 . it's better experience when the amount is equal to 0 not be visible .
I think it has a simple solution but I can't see it .
do you have any idea ?
Your code works fine! If you want to make it simpler, there's a bit of repeated logic you could condense into one function that handles the situations:
fun adjustValue(amount: Int) {
val adjusted = number + amount
if (adjusted > 5) // show Toast
number = adjusted.coerceIn(0, 5)
view.text_amount.text = number.toString()
view.text_amount.visibility = if (number == 0) View.GONE else View.VISIBLE
}
view.minus_btn.setOnClickListener { adjustValue(-1) }
view.plus_btn.setOnClickListener { adjustValue(1) }
basically the idea is you work out the new value (I'm using a temporary variable so we never set number to an invalid value) and show whatever warnings you need to. Then the coerceIn line makes sure we lock it within the valid range of allowed values.
You could do if/else checks and only set the new value if it's a valid one, but sometimes it's simpler and shorter to just set things and then worry about the edge cases, so this is just an example of that!
Same thing for the TextView bit - it's easier to just set the value whatever it is, and then set whether it should be displayed or not. You could use if/else branches to look at the value and decide whether to set the text or not... but why make your life hard? We know the value's in the valid 0 to 5 range, we can hide it if it's 0 and show it otherwise... easy!
You could make the function take a Boolean instead, like plus: Boolean and then go val adjusted = number + if (plus) 1 else -1, but making it an Int means you could easily add a +10 button or whatever without adding any more code or any more validation logic, and it's not any more complicated to pass in -1 instead of false (arguably it's clearer!)
that's probably more than you were asking for but hopefully it's useful. If nothing else, the "just set the text and the visibility every time" approach is good and neat
Decrease the value of text_amount only if it contains a value greater than 0 and after that check again its value and if it is 0 then hide it:
view.minus_btn.setOnClickListener {
if (number > 0) {
number--
view.text_amount.text = number.toString()
if (number == 0) view.text_amount.visibility = View.GONE
}
}
The following code (simplified example):
/** Determine if a is less than 15 and b is more than 15. **/
fun isFifteenBetween(val a: Int, val b: Int) {
if((a < 15) && (b > 15)) { return(true) }
else { return(false) }
}
should make isFifteenBetween(3, 20) return true, and isFifteenBetween(20, 3) return false. However, I get the following recommendation from Android studio (v3.4):
Return should be lifted out of 'if'
Inspection info: This inspection reports if, when and try statements
that can be converted to expressions by lifting a return or an assignment out.
Typical example:
fun foo(arg: Boolean): String {
when (arg) {
true -> return "Truth"
false -> return "Falsehood"
}
}
The only related question I have found at stackoverflow is Kotlin: Return can be lifted out of 'when', but this doesn't quite seem to cover my case, I think.
How should my code be written? I don't understand how the 'when'-expression provided by Android studio is supposed to fit in my case.
Is the recommendation from Android studio simply a matter of taste and comfort, or will a change of code in this case actually make an impact on performance?
Are there any guidelines available for best practise?
The official convention is to prefer to return the expression itself:
https://kotlinlang.org/docs/reference/coding-conventions.html#using-conditional-statements
This said the example from android studio should become:
return when (arg) {
true -> "Truth"
false -> "Falsehood"
}
This will change the code of isFifteenBetween to:
/** Determine if a is less than 15 and b is more than 15. **/
fun isFifteenBetween(val a: Int, val b: Int) {
return if((a < 15) && (b > 15)) true
else false
}
In terms of performance, both alternatives are almost equivalent.
These answers could be a little influenced by my opinion. but I think is more or less the reason behind. The fact of return the expression give direct impact while reading the piece of code. You know the result of the statement will be exhaustive and you have the information that every branch has been treated.
I consider this a best practice because in some case making a branching condition exhaustive could make the compiler give you an error while forgetting some new conditions. More than all for sealed classes. Further reading: https://proandroiddev.com/til-when-is-when-exhaustive-31d69f630a8b
The message is quite clear:
This inspection reports if, when and try statements that can be
converted to expressions by lifting a return or an assignment out.
And it states the fact that:
In Kotlin, if is an expression, i.e. it returns a value.
You can find more here: https://kotlinlang.org/docs/reference/control-flow.html#if-expression
In your case, you can return the result like this:
return if((a < 15) && (b > 15)) true else false
So this:
if((a < 15) && (b > 15)) true else false
is an expression and its value is returned by return.
This expression can be further simplified (but it's not related to your question):
return (a < 15) && (b > 15)
In Kotlin when replace switch-operator from java, but main difference is that when is an expression, therefore it can return result.
To better understand how does work when-expression in Kotlin, you can have a look on lambdas. The when-operator just returns result of its 'lambda' after each case.
Even if you write
when(a) {
1 -> println("one")
else -> println("something else")
}
This notation returns result of function println(...), that returns Unit. Therefore it isn't the best way to write code, when you duplicate this 'return'.
val result = when(a) {
1 -> println("one")
else -> println("something else")
}
// and now result equals to Unit-object
The same story is with if-else, that is also expression.
I am 99% sure that this cannot be done, however I thought I would ask to be certain.
I am attempting to create an application that calculates the required dice roll for an action in a popular tabletop war game.
The following is this calculation in Java
int x = ((WSattacker * 2) - WSdefender);
int y = (WSattacker - WSdefender);
String result;
// Calculation for a +5
if (x <= -1) {
result = "5+";
}
// Calculation for a +4
else if (x >= 0 && y <= 0) {
result = "4+";
}
// Calculation for a +3
else if (y > 0) {
result = "3+";
} else {
result = "Error";
}
return result;
Now my issue is that to avoid copywriter infringement I cannot mention the name of the game in my application, and probably cannot hard code the above calculation in the app.
This means that it is difficult to tell a potential user what the app will do.
The only solution I can think of is to make the application generic and allow the user to input the calculation required in the form of an equation.
An equation that I can place anonymously on a public board or similar.
Therefore my questions are as follows.
Is there another way of going about this?
If no, is it possible to condense the above code into a single expression/ equationi.e. one that removes the if and else statements
To answer question 2:
result = test_condition_1 ? result2_if_true : (test_condition_2 ? result2_if_true : test3_or_result2);
You can then build up 'compound' test conditions this way, and it's based upon ternary operators.
EDIT
Ternary operators are a short-hand way of writing if..then..else statments, and more information can be found in the wiki-link above. An example of its use is below, which you can compile and run:
public class TernaryTest {
public static void main(String [] args){
int x = 14;
int y = 5;
String result = ( x <= 10 ) ? "Less than 10" : "More than 10";
System.out.println("Result is: " + result);
}
}
Try running it and see the result as you change the value of x to understand how it works. Then it's possible to extend it to include and else by replacing the "more than 10" string.
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.
This is a performance critical part of my android application, and I am using the NDK (c) to process a large bitmap array.
int blender(const char* blendMode, int c1, int c2, int amount){
int sob, sog, sor, soa, dsr, dsg, dsb, dsa = 0;
dsr = Argb_GetRed(c1);
dsg = Argb_GetGreen(c1);
dsb = Argb_GetBlue(c1);
dsa = Argb_GetAlpha(c1);
sor = Argb_GetRed(c2);
sog = Argb_GetGreen(c2);
sob = Argb_GetBlue(c2);
soa = Argb_GetAlpha(c2);
int src_alpha, mix_alpha, dst_alpha;
src_alpha = soa * ((255 * amount) / 100) >> 8;
if (!strcmp(blendMode, "normal")) {
PSD_BLEND_NORMAL(dsr, sor, mix_alpha);
PSD_BLEND_NORMAL(dsg, sog, mix_alpha);
PSD_BLEND_NORMAL(dsb, sob, mix_alpha);
}
else if (!strcmp(blendMode, "exclusion")) {
mix_alpha = soa / 255;
//.... it's not always just the 3 macros
PSD_BLEND_EXCLUSION(dsr, sor, mix_alpha);
PSD_BLEND_EXCLUSION(dsg, sog, mix_alpha);
PSD_BLEND_EXCLUSION(dsb, sob, mix_alpha);
}
~~~~~~~~~ X 20 or so blend modes ~~~~~~~~~~~~
}
Currently it's running this blender function on every pixel, and doing a switch (clearly inefficient)
also, it has to take the original command as a string (From json, and passed down through java)
I can think of a couple ways to make it more efficient, but they all involve writing 2 giant switch statements. I would prefer to use 1 switch statement, or lookup if possible
Thank you!
Pretty nasty problem but I got a "hackish" idea.
If the 'blendMode' names are chosen nicely, you could compare only the first two (or three) letters of the strings. If there are multiple strings with same first letters, you could make a special case and compare first and third letter and so on.
This trick would make the code a lot faster than calling strcmp() all the time. Also inlining the compare function might help too.
Here is some code:
/* compares first two letters of the string */
inline int fast_cmp(const char *mode, const char *cmp) {
return (mode[0] == cmp[0] && mode[1] == cmp[1]) ? 1 : 0;
}
if( fast_cmp(blendMode, "no") ); /* for "normal" */
if( fast_cmp(blendMode, "ex") ); /* for "exclusion" */
In action: http://ideone.com/OiXS0
Ofcourse the comparisons could be written directly into if / else statements but it might get confusing. This can be fixed with small and nifty macro:
#define FAST_CMP(x, y) x[0] == y[0] && x[1] == y[1]
And here is the macro in action: http://ideone.com/NQFwW
This macro version is perhaps the fastest way to do the comparison.