Counting how many times a condition statement in while loop is ran - java

This will count how many times the while loop ran when true, however, I am trying to count how many times the num==0 test is performed. The num integer will change.
int counter = 0;
while (num == 0) {
doSomething();
counter ++;
}
This is an alternative I came up with, but seeking a better way to do it.
int counter = 0;
do {
if (num == 0) {
doSomething();
counter++;
} else {
counter++;
}
} while (num == 0);

Given the loop:
while (num == 0) {
doSomething();
counter ++;
}
The check num==0 will be performed once for every iteration, then once more after the last iteration. That last check is the one that prevents the while from being executed again.
So if counter is equal to 3, that means that we had 3 full iterations of the loop (3 checks whether num==0), followed by a fourth check that prevented us from going into the loop again.
It isn't clear to me what your second code snippet is trying to achieve.
if (num == 0) {
doSomething();
counter++;
} else {
counter++;
}
Is 100% equivalent to
if (num == 0) {
doSomething();
}
counter++;
And after every iteration of the do...while() there will still be a check for num==0 due to the loop condition.

If you want to count the number of times a particular if condition is checked (inspected) within a while loop then place a counter variable (that increments by 1: counter++;) directly above that if statement line within the loop since any conditional statement can potentially abruptly break out of or continue the loop within its code block if that particular condition is true.
This counter variable will need to have been declared and initialized to 0 above the while loop. Here is an example:
int counter = 0;
while (num == 0) {
if (doSomething == true) {
continue; // counter can not increment. Goes to next iteration.
}
if (doOtherThing.equals("no") {
break; // counter can not increment. Exits loop.
}
counter ++; // counts the number of times the following IF was checked.
if (n == 0) {
doSomthingCool();
num++; // increments num to 1 and loop will exit on next iteration attempt.
}
}
The above counter simply indicates that the IF condition following the increment of that counter will definitely be inspected...not found to be true and its' code block entered and run. It basically indicates that the condition will definitely be looked at.
This is fine and well until you start dealing with else if. What if you wanted to know if the ELSE IF was checked? Was the IF inspected or the ELSE IF? You still don't want to know if the condition was true and the code block for that statement was entered, you just want to know if the condition was looked at and checked.
One way to overcome this situation is to apply the counter directly into the condition for that statement. This can be done but the counter condition portion should always be equal to true and be the first condition encountered followed by && (AND) within the overall conditional statement, this way all other conditions will be checked in their original sequential order:
if ((ifCounter == ifCounter++) && someNum < 3) { ... }
else if ((elseCounter = elseCounter++) && someNum < 10) { ... }
Here is a runnable example:
int num = 0;
int counter = 0; // The Overall iteration counter
int doSomethingCounter = 0; // The doSomething condition counter
int doSomeOtherThingCounter = 0; // The doOtherThing condition counter
int ifCounter = 0; // The IF someNum condition counter
int elseIfCounter = 0; // The ELSE IF someNum condition counter
int someNum = 0;
boolean doSomething = true;
String doOtherThing = "yes";
while (num < 10) {
counter++;
if ((doSomethingCounter == doSomethingCounter++) && doSomething == true) {
doSomething = !doSomething;
continue; // Counters can not increment. Goes to next iteration.
}
if ((doSomeOtherThingCounter == doSomeOtherThingCounter++) && doOtherThing.equals("no")) {
break; // Counters can not increment. Exits loop.
}
// Counts the number of times the following IF condition was checked.
if ((ifCounter == ifCounter++) && someNum < 4) {
someNum = doSomethingCool(someNum);
}
// Counts the number of times ELSE IF condition is checked.
else if ((elseIfCounter == elseIfCounter++) && someNum > 0) {
/* increments num by 1 until it reaches 10 then loop
will exit on next iteration attempt. */
num++;
}
}
System.out.println("The WHILE loop has done a total of: " + counter + " iterations.");
System.out.println("The doSomething IF condition was checked: " + doSomethingCounter + " times.");
System.out.println("The doOtherThing IF condition was checked: " + doSomeOtherThingCounter + " times.");
System.out.println("The someNum IF condition was checked: " + ifCounter + " times.");
System.out.println("The someNum ELSE IF condition was checked: " + elseIfCounter + " times.");
When the above code example is run the console window will display:
The WHILE loop has done a total of: 15 iterations.
The doSomething IF condition was checked: 15 times.
The doOtherThing IF condition was checked: 14 times.
The someNum IF condition was checked: 14 times.
The someNum ELSE IF condition was checked: 10 times.

int num = 0;
int counter = 0;
while(num==0) {
if (num == 0) {
doSomething();
} else {
}
counter++;
//if the counter inc then the above condition statement should been executed.Make sure this doesn't take break into consideration.
}

Related

While loop not looping after script finishes

I have 2 while loops, the first while loop is supposed to take the scanner input and loop around. Once the script is finished for the second while loop, my code stops.
while (timesLooped < loopTimes) {
while (loss < 2) {
Thread.sleep(10);
Random randomGenerator1 = new Random();
Random randomGenerator2 = new Random();
int n = randomGenerator1.nextInt(max);
int b = randomGenerator2.nextInt(max);
if (n == 1 && b == 1) {
loss = loss + 2;
System.out.println("You got snake eyes and lost!");
} else {
score = score + n + b;
}
System.out.println("You got: " + n + b);
System.out.println("Your new score is: " + score);
}
timesLooped = timesLooped + 1;
}
loss is never reset. After it completes the inner while loop once, it never runs it again since the condition always stays false. You add an additional print statement to confirm this is what happens:
while (timesLooped < loopTimes) {
// Once this finishes loss remains the same
while (loss > 2) {
// Etc...
}
// Add a print statement so we can observe it running multiple times.
System.out.println("Ran outer loop!");
// You need to reset loss after running the loop
// loss = 0;
timesLooped = timesLooped + 1;
}

Using modulus operator in for Loop with if statements - Java beginner

I hope someone can help. My problem is with using the modulus operator in a for loop. My code is as follows:
for (int i = 0; i < 10; i++)
if (i % 2 == 0) {
method1();
}
else {
method2();
}
I understand how this loop works in that it iterates between if and else because of the even and odd numbers created by the condition that uses
the modulus operator (i % 2 == 0)
However, I want to create a condition using the modulus operator so that my loop iterates through 4 methods - as in:
loop starts{
method1();
method2();
method3();
method4();
loop repeats
}
I can't work out how to accomplish this. I would appreciate any help and advice.
Thanks in advance.
Put j = i % 4
And check for method1() j should be equal to j = 0, similarly for
Method2() check j = 1. And so on. Put for range conditions to 1 for infinite loop or desired range.
You could be looking to use the switch statement. More on that here.
Basically it takes a variable to switch between cases.
For example:
for(int i = 0; i < 10; i++){
switch(i%2) {
case 0: method0();
break;
case 1: method1();
break;
}
}
Here is the out put if method0 printed 0, and method1 printed 1:
1
0
1
0
1
0
1
0
1
0
You can edit the modulus to whatever number you want, you just have to account for the different possibilities.
Do you mean something like this?
for(int i = 0; i < 10; i++)
{
if(i%4 == 0)
{
condition
}
else if(i%4 == 1)
{
condition
}
else if(i%4 == 2)
{
condition
}
else if(i%4 == 3)
{
condition
}
}
Remember to put it on paper if you're confused and loop through your head (as a beginner)

Continue statement in Java

I adding a continue statement to end the current iteration so that the rest of the statement in the loop body is not executed.
public class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println(sum);
}
}
The things I can't understand is why I will get error if I added {} ?
public class Main {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11) {
continue;
sum += number;
}
}
System.out.println(sum);
}
}
Error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable code
at Main.main(Main.java:18)
This will work.
if (number == 10 || number == 11) {
continue;
}
sum += number;
Explanation
When you don't add {} to your if statement, only the next line will be considered. Therefore, you need to leave sum += number outside the {}
Because continue statement is final in your branch (between {}), so next statement (sum += number) will not execute never. Your IDE must warn you of that, that's why it didn't compile it and you got error.
In your first block, the one without { you effectively wrote:
if (number == 10 || number == 11) {
continue;
}
sum += number;
The sum += number is reachable, as long as the expression is false.
In the second you actually wrote:
if (number == 10 || number == 11) {
continue;
sum += number;
}
The sum += number; has become unreachable because if the expression is true it will always be skipped because of the continue, and if the expression is false it will not be executed because it is not in the block statement.
As other answers said correctly, only the first line of code will be run after an if statement. However, another rule is that you cannot add any more lines of code after the "continue" statement in an if statement. So, that is really the error. If you were to tweak the code to switch the "sum += number;" with continue, you won't receive the same error. Hope this helps.
You execute sum += number; inside curly brackets ({}) of your if-block:
if (number == 10 || number == 11) {
continue;
sum += number;
}
This will work:
if (number == 10 || number == 11) {
continue;
}
sum += number;

Getting a while loop to continue with a if statement

I'm working with a while loop and an if statement.
I want the loop to continue if the else statement is being run. In my understanding the "continue;" should restart the loop, but it doesn't.
I found one workaround to fix this though, it's to set "cho = 1;". But is this really necessary? Are there any more logic ways to solve this problem?
Thanks!
while (sum < 21 && cho == 1 && sum != 21) {
System.out.println("Do you want to (1)hit or (2) stay?");
cho = scan.nextInt();
if (cho == 1) {
getCard(index++);
if (sum > 21) {
System.out.println("You busted! Dealer wins.");
return;
}
} else if (cho == 2) {
System.out.println("Your value is " + sum);
sum = playerTotal;
}
else{
cho = 1;
System.err.println("The input value given is not a valid integer");
continue; //Does not restart the loop.
}
}
A continue jumps back to the condition of the loop which is then evaluated again. If the condition evaluates to false, the loop will obviously not be run again.
So if you want your loop to continue actually looping, you have to make sure that the condition is true.
This means: You have to set cho = 1 and make sure sum < 21
Also note that the sum != 21 in your condition is not needed, since sum < 21 already eliminates that possibility.

how many loops is this running? - java coding

I have been given "10 broken loops" to solve. I need to comment what was changed to make them correct.
I have
public class BrokenLoops {
//loop 5 times
public static void loop1() {
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
I know what the problem is, it will never be 10. 1 then 3 then 7 then 9 then 11 etc.
What I don't know is how many loops will be run if I type either !=9 or !=11
Would the code run as
If the code has !=11, would it run as
i = 1 "in loop"
1 = 3 "in loop"
i = 5 "in loop"
i = 7 "in loop"
i = 9 "in loop"
i = 11 "out of loop"
and so, there are 6 loops? The correct answer for 5 loops would be !=9?
Thanks in advance
This loop have condition to run when i is not equal 10. Because i starts at 1 and increases by 2 on every iteration, i will be always odd number and therefore can newer equal 10. So condition for loop will be always true. Simply put: your loop will go indefinitely.
About for statement from
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
The termination expression is invoked before each iteration. When it evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
More info about for statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
//edit
Correct code for 5 loops if you have to use '!=' comparison would be:
for(int i = 1; i != 11; i += 2)
// i==1 PASS
// i==3 PASS
// i==5 PASS
// i==7 PASS
// i==9 PASS
// i==11 FAILED, Loop ends here
although it's better to use
for(int i = 1; i < 10; i += 2)
//or
for(int i = 1; i < 11; i += 2)
this way, your loop will end after 5 loops and safer for many reasons
The loop as you have posted will run continuously as i will never get the value 10.
if you make the termination condition i != 9 then the loop will run for 4 times.
if you make the termination condition i != 11 then the loop will run for 5 times.
if you make the termination condition i <= 10 then the loop will run for 4 times.
to get it to run 10 times, change the for loop to this:
for (int i = 1; i <= 10; i++){
//Your code
}
EDIT:
Code:
for (int i = 1; i != 11; i += 2)
{
Console.WriteLine("In loop {0}", i);
}
Console.WriteLine("Out loop");
Console.ReadLine();
Output:
There are a few possible ways to solve your question.
Example 1
If you only need to get in the loop 5 times you can simple change your code to:
//loop 5 times
public static void loop1() {
for (int i = 0; i < 5 ; i++) {
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will print something like:
In loop 0
In loop 1
In loop 2
In loop 3
In loop 4
Out of loop
Example 2
Another option would be to change your termination value to !=11(Just don't forget, that if you increment would become i += 3 for example, this will become an infinite loop again):
public static void loop1() {
for (int i = 1; i != 11 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
This will terminate the loop once i will be equal to 11, so the output would be:
In loop 1
In loop 3
In loop 5
In loop 7
In loop 9
Out of loop
Example 3
You can also change termination to i < 10(or <=9 or <=10 or <11):
public static void loop1() {
for (int i = 1; i < 10 ; i += 2) { //final statement i += 2 means i+2
System.out.println("In loop "+i);
}
System.out.println("Out of loop");
}
The output will be same as in Example 2.
Example 4
You can also add a check inside your loop to stop it after something evaluates to true:
public static void loop1() {
int checkInt = 0;
for (int i = 1; i != 10 ; i += 2) { //final statement i += 2 means i+2
if (checkInt == 5) break;
System.out.println("In loop "+i);
checkInt++;
}
System.out.println("Out of loop");
}
So when checkInt will be equal to 5(loop was made 5 times), the loop will just stop. Output is the same as in Example 2 and Example 3
If the code has i !=11, would it run as
You just have to use i<10 to get the desired result

Categories