This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 7 years ago.
I understand that there are a number of questions on this topic on StackOverflow. But I am still slightly confused and unsure of when to use the operations. I am going through old tests in studying for my exam. One of the methods returns the number of classrooms that are handicapped accessible and are available. I wrote the counter method but am not sure if I am supposed to pre-increment or post increment the counter. I am confused as to how it works with return statement in methods. I still do not get what value the method will return below. The other questions do not show return values in methods and thus I am confused as to practically how it works. Here is the code:
public int howManyHandi()
{
int counter= 0;
for (int i = 0; i < _clsrms.length; i++){
if (_clsrms[i].handicappedSuitable() && _clsrms[i].isAvailable()){
++counter;
}
}
return counter;
}
PRE-increment is used when you want to use the incremented value of the variable in that expression., whereas POST-increment uses the original value before incrementing it.
Whenever your code encounters a PRE-increment, it increments the value of that variable in the memory, then load that value and continues reading the expression.
POST-increment does the opposite, it loads that value of that variable in the memory, then increments the value and continues reading the expression.
To make it more clear, consider this
int i = counter++;
is equivalent to
int i = counter;
counter = counter + 1;
WHEREAS
int i = ++counter;
is equivalent to
counter = counter + 1;
int i = counter;
EDIT: My StackOverflow comments arent working, so I'll just edit it here.
What I'm saying it, it only matters when you use that value in an expression.
sum = 0
counter = 0;
sum = (++counter)+(++counter)+(counter++)
evaluates as
sum = 0
counter = 0
//For first ++counter
counter = counter + 1
sum = counter
//For second ++counter
counter = counter + 1
sum = sum + counter
//For first counter++
sum = sum + counter
counter = counter + 1
In your example it doesn't matter, since you do nothing with the value returned by ++counter.
The only time it makes a difference is when you are using the value returned by the post/pre-increment operator.
For example, if you had a return counter++; or a return ++counter; statement, your method would return a different result based on which operator you used.
Related
This question already has answers here:
Java integer-double division confusion [duplicate]
(5 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
The code is supposed to double the mean and provide a score, i.e. 4.2231 is mean, but this code prints 4.0.
public Double mean(){
return Double.valueOf((sum() / sequence.length));
}
For this line, for example, 1 is the sequence.length.
It should print out "is wobbly" when sequence.length is less then 1 or when the list of numbers have no particular order, but this code makes it print out increasing. How do I make it so when sequence.length = 1, print wobbly. Or how should I improve my decreasing code to avoid that breach in the future
public boolean isIncreasing() {
int temp;
boolean flag = true;
for (int index = 0; index < sequence.length - 1; index++) {
temp = sequence[index];
if (temp > sequence[index + 1])
{
flag = false;
break;
}
}
return flag;
}
In java, in order to make a division return a double value, you need that divisor or dividend is a double, so for your case this should work:
return (Double.valueOf(sum()) / sequence.length);
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 3 years ago.
Improve this question
The following is a lab more my Intro to Java class. It's my first Java class and I'm beyond stuck. I have a few lines of code but nothing noteworthy.
Solve below problem using ‘do-while’ and random number generator.
Simulate rolling a pair of dice 10,000 times and counts the number of times doubles of are rolled for each different pair of doubles.
Your program should roll two dice using the Random object (that is, generate two numbers between 1 and 6)
Define 6 counters variables
If the dice match (both should be same 1-1, 2-2, 3-3...), then increment a specific counter [you can use ‘if’ or ‘switch’ for condition check (dice1==dice2) and counter increment.
Display the results after the loop completes 10,000 times.
1-1 displayed: 30 times
2-2 displayed: 100 times
...................
6-6 displayed: 890 times
Code:
public class DiceRoll {
public static void main(String []args){
int x = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
do {
int dice1 = (int)(Math.random()*6)-1;
int dice2 = (int)(Math.random()*6)-1;
if (dice1 == dice2){
if (dice1 == 1){
counter1++;
}
if (dice1 == 2){
counter2++;
}
if (dice1 == 3){
counter3++;
}
if (dice1 == 4){
counter4++;
}
if (dice1 == 5){
counter5++;
}
if (dice1 == 6){
counter6++;
}
}
} while (x > 10000);
System.out.println("Results:");
System.out.println(" ");
System.out.println("1-1 displayed: " + counter1);
System.out.println("2-2 displayed: " + counter2);
System.out.println("3-3 displayed: " + counter3);
System.out.println("4-4 displayed: " + counter4);
System.out.println("5-5 displayed: " + counter5);
System.out.println("6-6 displayed: " + counter6);
}
}
Okay, I don't want to just give a solution, so I am going to attempt to walk you through it. (Sorry if I tell you something you already know)
1. The Random object. This is an instance of the Random class. You need to create a variable of type random and assign it to a Random object.
Random dice = new Random();
Do this outside of the do-while loop, so that you aren't generating a new instance of Random and assigning the dice variable to that each time.
2. You are then going to need to generate random numbers using this object. If you look in the documentation you will find one method that returns an int within a user specified range:
nextInt(int bound)
To generate a random number, call this off of dice and store the return in another variable:
int rollOne = dice.nextInt(6)+1;
The reason you are adding 1 to the answer is that nextInt returns a value between zero and the given value exclusive.
3. The do-while loop. This loop executes once, then checks the conditional after the while keyword before every subsequent execution (to see if it should execute again).
You need the loop to execute 10,000 times.
int rolls = 0
do {
rolls++; // Increments rolls by one
} while(rolls < 10,000); //It starts at one, so this will loop 10,000 times
4. What to put in the loop: Every iteration, you need to roll the dice twice (use nextInt twice), compare their values, and increment the appropriate counter.
Okay, now that I have seen your code, your problem is simple:
You need to increment x in the loop, perhaps right after the
do {
line. You also need to edit the conditional in the while part. It should be
} while (x < 10000); //Less than, not greater than >
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 4 years ago.
class Test {
public static void main(String[] args) {
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
}
}
}
The output here is 1,2 and 1,3. We are doing post-increment and pre-increment in both the cases why I am getting different results?
Because post increment happens at the end of the iteration.
Hence the below code :
for (int i= 1; i < 2; i++) {
System.out.println(i);
System.out.println(++i);
Will work something like this:
int i = 1;
System.out.println(i); // i is still 1
System.out.println(++i); // pre increment making i to 2 and then print
i++;
if(i<2)
// iterate again
However, in second case:
int a = 1;
System.out.println(a++); // post increment first print 1 and then change a to 2
System.out.println(++a); // pre increment a now changed to 3
System.out.println(i); // 1 (initial value)
System.out.println(++i); // 2 (pre increment returns the value after increment)
int a = 1;
System.out.println(a++); // 1 (initial value prior to increment, since post increment
// returns the value prior to increment)
System.out.println(++a); // 3 (pre increment returns the value after increment)
The i++ in the loop's definition only takes place at the end of each iteration. You never print the value of i after i++ is executed, since the loop terminates after the first iteration.
BTW, if i++ was executed prior to System.out.println(i);, you'd still get a different output (compared to the last two println statements) - 2 followed by 3.
The general structure of a for loop (more precisely: this type of basic for statement) is:
for ([ForInit]; [Expression]; [ForUpdate]) Statement
The equivalent while loop is:
[ForInit];
while ([Expression]) {
Statement;
[ForUpdate];
}
In other words, the update is executed after the loop body.
So your code is equivalent to:
// ForInit
int i = 1;
while (/* Expression */ i < 2) {
// Statement
System.out.println(i);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
// ForUpdate
i++;
}
Hopefully it is then easy to see why there is a difference in the output.
In the first case, the post-increment is not called. If you understand how a for loop works, you will know that the increment section is not executed the very first time. The initialization section, here int i = 1, and the condition checking - i < 2 is validated. The increment section is invoked only after each iteration.
In the second case, the post-increment is performed and hence the difference in values. You should focus more on the basics of looping.
System.out.println(i);
i isn't postincremented here. The answers would be the same if it were:
System.out.println(i++);
System.out.println(++i);
int a = 1;
System.out.println(a++);
System.out.println(++a);
for (int i= 1; i < 2; **i++)**
doesn't do anything until a pass through loop is done.
http://puu.sh/8ekfm.png
Zonko's government (The Kingdom of Zumbania) decided to ban directly adding numbers greater than 1 to other numbers. Zonko decided to create his own addition method (for positive integers) to circumvent the ban. Can you help finish his code?
To get the sum of a and b, Zonko starts by setting a variable sum equal to a. He then repeatedly adds 1 to sum until it reaches a+b. 1 is added every iteration of the loop until its been added the right number of times. What is the correct condition in the loop so it stops at the right time?
public int add(int a, int b){
int sum = a;
for(int i=1; LOOP-CONDITION; i=i+1){
sum = sum + 1; //this will add 1 to sum every iteration
}
return sum;
}
Can someone explain this and tell me how they got the answer?
The Java idiomatic for loops to perform an action a certain number of times are:
for(int i=1; i <= [numTimes]; i=i+1){
and
for(int i=0; i < [numTimes]; i=i+1){
The former has the correct starting condition, so your loop condition would be: i <= b.
The trick is in the words :
Zonko's government (The Kingdom of Zumbania) decided to ban directly
adding numbers greater than 1 to other numbers.
This means a cannot be added to b directly when b is greater than 1.
Assume you want to add a = 5 and b = 3. You can get the answer by adding 1 to 5 three times.
a = 5;
loop(b times){
a = a + 1;
}
Here is how the loop will go:
a = 5;
loop starts
a = 5 + 1;
a = 6 + 1; // we made it 6 in previous step
a = 7 + 1;
loop ends
This question already has answers here:
for loop terminating early when comparing to Integer.MAX_VALUE and using System.out.println
(2 answers)
Closed 9 years ago.
I'm trying to work out why this loop terminates...
#Test
public void test() {
int counter=0;
int from = 0;
int until = Integer.MAX_VALUE;
while(counter <= until) {
counter++;
if(counter < from) {
System.out.println("continuing " + counter + " <= " + from);
continue;
}
}
System.out.println("finished " + counter);
}
while(counter <= until) should always resolve to true because the counter cannot be increased beyond Integer.MAX_VALUE. Thus, the loop should not terminate.
However, in Eclipse, if I run with the JUnit runner I get:
finished 108772
If I run in the debugger I get:
finished 125156
The output in the if(counter < from) is never output. If I remove that block the code still terminates, this time at Integer.MAX_VALUE.
finished 2147483647
not really sure what you are trying to do here your while loop will work as expected but the from will never change so the "counter less than from" wont ever be executed?
until (max int) will be = 2147483647
if you change the while loop to (counter < until) you get the output text of "finished 2147483647"
that help?
I can't reproduce your output so this is not an answer, just an observation. Consider just these lines.
int counter=0;
int until = Integer.MAX_VALUE;
while(counter <= until) {
counter++;
The while condition is 'less than or EQUAL'. So when counter is equal to Integer.MAX_VALUE one is added to it. This produces the largest possible Java negative number. Keep adding one to this value and it will eventually become zero, then count up once again until it reaches Integer.MAX_VALUE. Then the whole sequence starts over again. It looks like an infinite loop to me.
You would also execute the 'continuing' line on each iteration while counting up from the largest negative number.