i++ and ++i in Java [duplicate] - java

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 2 years ago.
int i = 1;
i = i++;
int j = i++;
int k = i + ++i * i++;
System.out.println("i==" + i);
System.out.println("j==" + j);
System.out.println("k==" + k);
Why the result of k is 11? I'm a learner of java. Please help me and explain what's going on under the hood or give me some pointers about where I can find related learning resources if possible.

int i = 1; // i == 1
i = i++; // i is incremented, but the original value of i is assigned back to i, so i == 1
int j = i++; // i == 2
int k = i + ++i * i++; // k = 2 (the original value of i before this statement) +
// 3 (the result of pre-incrementing i) *
// 3 (the result of post-incrementing i is still 3) == 11
System.out.println("i==" + i);
System.out.println("j==" + j);
System.out.println("k==" + k);
Note that 2 + 3 * 3 is evaluated as 2 + (3 * 3).

Related

How I can sum all numbers in array and print them as integer value in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
enter code hereI have this number "811218-3476"as string,I want to multiply 8 by 2,1 by 1, 1 by2, 2 by1 and so on as following:
8 1 1 2 1 8 3 4 7 6
2 1 2 1 2 1 2 1 2 1 *
16 1 2 2 2 8 6 4 14 7 ----> Result
My question is how I kan do sum for the result, I did sum one number with another number like
16 + 1+2+2+2+8+6+4+14+7 = 62,
but I want to do sum as following:
1+6+1+2+2+2+8+6+4+1+4+7 = 47.
I do not need you to write a code I have wrote it, but I want to know how I kan sum 1+6 instead of 16 as example. my code is here and it works fine.
I hope help know.
Thanks.
enter code here
public static boolean checknumber(String s) {
if(checkPersonNummer(s)== true) {
char [] charray = s.toCharArray();
int newch = 0 ;
int j = 0;
int i = 0;
String sum= "";
int x = 0;
for( j = 2; j < 8 ; j++) {
System.out.print(" "+ charray[j] + " ");}
for( j = 9; j < charray.length ; j++) {
System.out.print(" "+ charray[j] + " ");}
System.out.println(" ");
for( j = 2; j < 8 ; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
// System.out.println(" ");
for( j = 9; j < charray.length; j++) {
if(j%2 == 0) {
System.out.print(" "+ 2 + " ");
} else {
System.out.print(" "+ 1 + " ");
}
}
System.out.print("\n--------------------------------------------");
System.out.println("");
for( i = 2;i < 8;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 2;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 1;
sum += newch;
}
System.out.print(newch + " " );
}
for( i = 9;i < charray.length;i++) {
if(i% 2 == 0) {
newch = Character.getNumericValue(charray[i] )* 1;
sum += newch;
}
else {
newch = Character.getNumericValue(charray[i]) * 2;
sum += newch;
}
System.out.print(newch + " " );
}
System.out.println();
System.out.print("Total = " + sum);
}
return true;
}
}
This sounds like a homework assignment, and we're not a homework writing team. But I'll give you some basic advice.
First, I had one person tell me, "programming is the art of editing the null program until it does what you want". By that he meant that we start with a program that does nothing and slowly built it up.
That's a good way to start.
So... Start your program. You need to get your data in. Do that, and figure out how to print it.
After that, think about printing out each number times either 1 or 2 as your problem requires, and print each calculation as you go.
Then all you have to do is keep a variable outside of this loop to store the sum, and add each mini-calculation to it, then print it at the end.
Start small. Work up to the final answer. Lots of debug output while working on it.
Lets say I have an array of numbers [2,3,4,5,6], Think of this question as you are multiplying the numbers with 1 those are at odd position in the array and multiplying the numbers with 2 those are at even position in the array.
Answer to How to add 1 + 6 instead of 16
Check if the number is less than 10, if it is than you don't have to
worry about it But,
If the number is greater than 10 you can use the % operator.
For instance
15 % 10 gives you 5 and 15 / 10 gives you 1 that way you can separate two individual digits.

unexpected result while evaluating the operators

I have below code and it gives an unexpected result. To my understanding, the result should be 6 but its 1. Can someone help me how to get it?
int j = 0;
int i1 = j*5+ ++j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);
The difference between getting 6 and getting 1 is whether you think j*5 will be evaluated first or ++j will be evaluated first. The rule in Java is that subexpressions are evaluated in the order they appear in the expression if the order is not forced by dependencies. Here, j*5 appears first in the expression, so it is evaluated first. That gives the 1 result.
You have something like the code below:
int j = 0;
int i1 = j*5+ ++j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);
You need to edit your code to this:
int j = 0;
int i1 = ++j*5 + j;
System.out.println("j =" + j);
System.out.println("i1 =" + i1);
Your final output for "i1 =" + i1) will be 6.
The issue is that in your first code sample you are not incrementing J before you multiply it by 5 so you're only increasing it by +1 because you don't actually increment j until you've multiplied 0 * 5. (0 * 5) + 1 = 1. What I did was simply increment j (in prefix form) so that it increments by 1, and now you're multiplying (1 * 5) + 1.

Why does this code to generate 4 distinct random numbers throw an ArrayIndexOutOfBoundsException? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I'm trying to generate 4 random numbers without duplicates, using a loop, but I get an ArrayIndexOutOfBoundsException. Can someone please explain why?
// SECRET ANSWER
int secret[] = new int[4];
for (int i = 0; i < secret.length; i++) {
secret[i] = (int) (Math.random() * 6 + 1);
if (secret[i] == secret[i + 1] || secret[i] == secret[i + 2] || secret[i] == secret[i + 3]) {
secret[i] = (int) (Math.random() * 6 + 1);
}
if (secret[i + 1] == secret[i + 2] || secret[i + 1] == secret[i + 3]) {
secret[i] = (int) (Math.random() * 6 + 1);
}
if (secret[i + 2] == secret[i + 3]) {
secret[i] = (int) (Math.random() * 6 + 1);
}
}
So, imagine situation when you are on the last element in the array.
You try to get I+1, I+2, I+3 elements which do not exist. You need to change limit to length - 3 or do something similar
you mentioned array size 4 and you are trying to increase it that's why u are getting that exception.you can store only fixed size of elements in the array. It doesn't grow its size at runtime. To overcome this problem, use collection framework.
In the second iteration of the for loop, i is 1. The first two conditions in your 'or' chain are false, so the third is evaluated, which causes secret[i + 3] to be accessed. i + 3 is 4, but secret only has indexes 0 to 3. Your algorithm makes no sense.
This generates an array of 4 distinct, random numbers in the range [1..6]:
Random rand = new Random();
int[] secret = rand.ints(1, 7).distinct().limit(4).toArray();
Although, if you must use for loops, you should check all elements before the current index using a nested for loop, as this is all you need to check. You should also use a while loop to make sure you keep generating random numbers until you get one that hasn't been generated yet.
For example:
int[] secret = new int[4];
for (int i = 0; i < secret.length; i++) {
int n;
boolean distinct;
do {
distinct = true;
n = (int) (Math.random() * 6 + 1);
for (int j = 0; j < i; j++) {
if (secret[j] == n) {
distinct = false;
}
}
} while (!distinct);
secret[i] = n;
}

Java - Expected output after a loop printing array [duplicate]

This question already has answers here:
Java Increment / Decrement Operators - How they behave, what's the functionality?
(2 answers)
Closed 7 years ago.
I've seen this question (from a multiple choice) "what is the output of the following program" :
class array_output {
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i/2;
array_variable[i]++;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
The expected output is:
1 2 3 4 5
It is clear to me that the value i is incremented twice, first in the body of the loop and at the last line.
But I don't really get what the line array_variable[i]++; is doing.
Any suggestions?
Thanks in advance to answer to this newbie question!
The post-fix increment and decrement operators return the value of a variable before altering its value. Consider the following:
int anInt = 0;
System.out.println("anInt: " + anInt);
// anInt: 0
System.out.println("anInt: " + anInt++);
// anInt: 0
System.out.println("anInt: " + anInt);
// anInt: 1
System.out.println("anInt: " + ++anInt);
// anInt: 2
System.out.println("anInt: " + anInt);
// anInt: 2
So basically, anInt++ returns the value of anInt before incrementing it. ++anInt increments the value of anInt before returning the (freshly-incremented) value.
array_variable[i]++; increments the value that is stored in array_variable[i] by one.

Order of operations for compound assignment operators in Java

I came across the following on a mock exam recently, and was a bit lost as to why the answer given is 25, 25 according to the order of operations, and what I might be missing from the specification that gives the details as to why.
public class Test {
public static void main(String[] args) {
int k = 1;
int[] a = {1};
k += (k = 4) * (k + 2);
a[0] += (a[0] = 4) * (a[0] + 2);
System.out.println(k + " , " + a[0]);
}
}
Just looking at line 6 above I substitute the appropriate values, and get the following:
k = k + (k = 4) * (k + 2);
I evaluate the parenthesis first, which indicates k has first been assigned to the value of 4, and subsequently is added to the number 2, giving the total of 6. This is how I interpret that:
k = k + 4 * 6;
Now this is where it gets confusing. According to the order of operations I get the following, which would be correct given the previous expression:
k = k + 24;
In my thinking at this point k should be 4 because that was the new assignment, but the answer is actually 25, and not 28. Apparently compound operators have some order of precedence I'm not understanding, or my substitution principles are not correct.
In this answer, I will only consider the k case, it is the same for the array.
int k = 1;
k += (k = 4) * (k + 2);
// k += (k = 4) * (k + 2)
// 1 += (k = 4) * (k + 2)
// 1 += 4 * (k + 2) with k = 4
// 1 += 4 * 6 with k = 4
// k = 25
The tricks here:
k += captures the value of k before doing the calculation. += is called a compound assignment operator. Quoting the relevant part of the JLS:
the value of the left-hand operand is saved and then the right-hand operand is evaluated.
k = 4 returns the assigned value, so 4.

Categories

Resources