n = n--; why same value as before [duplicate] - java

This question already has answers here:
Difference between b=b++ and b++ [duplicate]
(4 answers)
What is x after "x = x++"?
(18 answers)
Closed 1 year ago.
The title is self-explanatory. Consider the following code:
int n = 5;
n = n--;
It gives n = 5.
As far as I understood the expression n-- is first evaluated, returning 5 (i.e. POSTdecrement). This expression gets assigned to the LHS, here n.
After this execution, n gets diminished. Thus I expected n = 4.
Why don't I see 4?

n-- yields 5 and then sets n to 4
n = sets n to the value of the right-hand expression, which is 5
Mixing the increment/decrement operators with an assignment to the same variable rarely does anything useful.

This is not fully correct, there is 2 forms to do it --n and n--, thats is where you will do the rest on N.
With the --n before you first rest and then return the value, and the other side is the opposite.
You first pass the value and then rest the value, try doing it the other way.

Given n=5, n-- return 5 but n value is 4.
Given n=5, --n return 4 and n value is 4.
That's why n has still the same vlaue

Related

In Java,operator precedence, increment and decrement, why isn't the first println statement executed? [duplicate]

This question already has answers here:
How increment and decrement with if condition
(2 answers)
Closed 5 months ago.
class Example{
public static void main(String args[]){
int x=99;
if(x++==x){
System.out.println("x++==x : "+x); //Why this code line is not run?
}
if(++x==x ){
System.out.println("++x==x : "+x);
}
}
}
Why isn't the first println statement executed?
The operands of an expression are evaluated left to right.
In the expression x++ == x, first x++ is evaluated. It increments x by 1, but returns the original value of x. So x++ returns 99.
Then x is evaluated, which returns 100 (since it was incremented by x++).
Since 99 is not equal to 100, this condition evaluates to false.
If you change the expression to x==x++, you'll get true.
The differece between i++ and ++i is very simple.
i++ - means exactly first get the value and then increment it for the further usage
++i - means exactly first increment the value and use the incremented value
Following the shippet x++ == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand and use it in the expression
Increment x and thus x == 100
Get x = 100 as the right operand (note it is already incremented)
99 != 100
Following the shippet ++x == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand
Increment x and thus x == 100 and use it in the expression
Get x = 100 as the right operand (note it is already incremented)
100 == 100
You can see all these logic. E.g. not experienced developer cannot know these details. Therefore the best practice is to avoid such increments in the expression. Just do it before the expression in the single line. In this case the logic will be straight forward and you get much less problems.

Result of function that includes pre- and post-increment differs

I had to understand some code which mixes pre- and post-increments in functions. There was one thing that confused me.
So I tried to test some smaller function. But I could not explain following behaviour:
int i = 1;
i = i++ * ++i * 2;
System.out.println("i = " + i);
int x = 1;
x = ++x * x++ * 2;
System.out.println("x = " + x);
The expected output was:
i = 8
x = 8
But actually is:
i = 6
x = 8
Can someone tell me why?
i++ * ++i * 2 --> 1 * 3 * 2 --> 6
++x * x++ * 2 --> 2 * 2 * 2 --> 8
Important values in bold.
The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes):
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
Source here.
In your specific case, as the postfix evaluates to the original value and the order of operations is left to right for same arithmetic operator - here, only multiplier applies - your operations are translated as above.
Post-increment increases the value of i but does not immediately assign the new value of i.
Pre-increment increases the value of i and is immediately assigned the new value.
Thus, in your example for y, after i++,
i has become 2 but it is still holding on to the previous value of 1.
When ++i occurs, i with the value of 2 will be increased by 1 and simultaneously, assigned the new value of 3. Therefore, 1 * 3 * 2 gives us the value 6 for y.
The same goes for x,
when ++x occurs, x is immediately assigned the new value of 2.
However, when x++ occurs, x is increased by 1 but is still assigned the previous value of 2. Therefore, 2 * 2 * 2 gives us 8.

Why is my implementation of math.random in my class only returning 0? [duplicate]

This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 2 years ago.
I've been trying to create a class to roll dice for games, and my code for one aspect of it is:
public int[] yahtzeeRoll() {
int[] rolls1 = new int[6];
for (int i = 0; i < 6; i++) {
rolls1[i] = ((int) Math.random()*6+1);
}
return rolls1;
}
yet, when I call it in the main method, it only returns 1 for each of the values. Why is this? How can I fix my code so that it generates 6 different numbers when I print the array in the main method?
You are casting the double value returned by Math.random() to int before multiplying by 6, and since Math.random() returns a value < 1, casting it to int results in 0.
Change
rolls1[i] = ((int) Math.random()*6+1);
to
rolls1[i] = (int)(Math.random()*6)+1;
The type casting by appending (type) takes precedence over the * 6 bits afterwards. Therefore, the result from Math.random() is always casted into 0 before you multiply it by 6, which turns out to always be 0 as well.
This answer points to this site which explains it quite well.
Either (int) (Math.random() * 6) + 1 or (int) (Math.random() * 6 + 1) would work as you have intended.
Math.random returns a floating point number between 0 and 1 but you are truncating it down to 0 by using (int) type cast before it. Use parentheses around your expression and then prepend (int) to that if you do wish to use integer truncation.
Btw, I think same sequence should be generated at each run if you don't seed the pseudo-random engine, say with current time or something.
Let's look at the expression.
((int) Math.random()*6+1)
Now Math.random() returns a double that is >=0 and <1.
You then cast that result to an int which means it will always become 0.
If you use.
(int)(Math.random()*6+1)
You are taking the double between 0 and 1, multiplying it by 6 (giving 0 ... 6) adding 1 and then casting to an int. This looks more like what you are looking for.
Math.random() returns double value in range [0, 1) (greater than or equal to 0.0 and less than 1.0). Then you cast that double value to int, so it always results in 0. After that you add 1 to it, so the result always remains 1.
You should cast result of multiplication - Math.random() * 6 instead of casting Math.random() return value:
rolls1[i] = (int)(Math.random()*6)+1;
By the way, you should be aware of operators precedence in Java language. You can have a look here: operator precedence to see nice table that shows that casting has a higher priority than multiplication and addition - this is the reason, why (Math.random()*6) is put in parenthesis for casting (this way you avoid casting only Math.random())
PS. There is also a link to table of operator precedence in official Java tutorial, but it doesn't exactly fit to your problem as it doesn't contain operation of casting - this is the reason, why I provided another link firstly.
You can take a clue from the below output presentation which is self explanatory.
Code:
double random = Math.random();
System.out.println("Math.random()>>"+random);
System.out.println("Math.random()*6>>"+random*6);
System.out.println("(int)(Math.random()*6)>>"+(int)(random*6));
System.out.println("Math.random()*6+1>>"+random*6+1); //+1 here is treated as a string by java and will add at the end of the number
System.out.println("(Math.random()*6+1)>>"+(random*6+1)); //number random*6 will be incremented by 1 as enclosing () will treat them as numbers
System.out.println("(int)(Math.random()*6+1)>>"+(int)(random*6+1));
Output:
Math.random()>>0.6793602796545469
Math.random()*6>>4.076161677927281
(int)(Math.random()*6)>>4
Math.random()*6+1>>4.0761616779272811
(Math.random()*6+1)>>5.076161677927281
(int)(Math.random()*6+1)>>5

Why does this expression keep evaluating to 0 [duplicate]

This question already has answers here:
Why does int exp1 = 14/20*100; equals '0' in java?
(4 answers)
Closed 7 years ago.
The following value1 keeps evaluating to 0, even though player1Disks and player2Disks are all above zero and not equal to one another.
int value1 = Math.round(100 * ((player1Disks - player2Disks)/(player1Disks + player2Disks)));`
Here are some example inputs for player1Disks and player2Disks respectively:
[5,8], [6,8], [8,4], etc.
However, all these are evaluating to zero. Am I missing something?
The integer division evaluates to 0 in the three cases you presented. 0*100 still equals 0.
You should multiply by 100 first, and then divide. Or better yet, don't use int.
First one: -3/13 = 0
Second one: -2/14 = 0
Third one: -4/12 = 0

What does someArray[--n] mean?

I tried googling this but Google doesn't handle "--n" well. I saw this in my professor's code:
f[--n];
f[n++];
where f is an array of double values.
My guess is that it returns the value of f[n] before reducing (or adding) to n.
f[--n]; means :
n = n -1;
f[n];
f[n++]; means :
f[n];
n = n + 1;
It's actually a type of operator called a pre-decrement, and it's part of a family of 4 operators (see table of java operators)
For an integer-type variable called n:
post-increment n++ is the equivalent of n = n + 1, the 'post' part means that if you see it in a line of code (ex. foo(n++);) then the line of code will be called Before n is incremented.
pre-increment ++n is also the same as n = n + 1 but it occurs Before the line of code it belongs in has been run.
post-decrement n-- is the equivalent of n = n - 1 and occurs After the current line of code has been run
pre-decrement --n is the equivalent of n = n - 1 and occurs Before the current line of code has been run
Example of post vs pre decrement:
int n = 5;
System.out.println(n--); //This prints 5
System.out.println(n); //This prints 4
System.out.println(--n); //This prints 3
System.out.println(n); //this prints 3
you can look it up under predecrement (--n) or postincrement (n++).
It works like this:
f[--n]: first n is reduced by 1 then the value of f[n] (this is already the reduced n) is returned
f[n++]: first the value of f[n] is returned then n is increased by 1
Example:
f {1,3,5}
n=1;
f[--n] returns 1
f[n++] returns 3
The code
f[--n];
f[n++];
Is the same as
n--;
f[n];
f[n];
n++;

Categories

Resources