Getting a while loop to continue with a if statement - java

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.

Related

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

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.
}

And / or in java

im having a problem in my java exercice
the question is saying
The program will end when the sum of even is >= 50 or the sum of odd is >= 49.
so while solving it i tried to use
while (sumeven < 50 || sumodd < 49 )
and it didnt worked at all but when i checked the solution they use
while (evensum <= 50 && oddsum<=49)
and it worked ( gave same answeres like the sample run)
so my question is did i misunderstood it ? or the question have some kind of a wrong given. thank you for your time
update:
the code :
package sample2;
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("enter the initial value");
int sumeven=0;
int sumodd=0;
int num;
int initial;
int div5and2=0;
initial=scan.nextInt();
if (initial<=0)
System.out.println("the number must be strictly positive");
else{
if (initial%2==0)
sumeven=initial;
else
sumodd=initial;
System.out.println("start entering your numbers");
num=scan.nextInt();
if (num<=0)
System.out.println("the number must be strictly positive");
else{
while(sumeven<=50||sumodd<=49 )
{
if (num%2==0)
sumeven=sumeven+num;
else
sumodd=sumodd+num;
if (num%5==0 &&num%2==0)
div5and2=div5and2+1;
num=scan.nextInt();
while(num<=0)
{
System.out.println("the number must be strictly positive");
num=scan.nextInt();
}
}
System.out.println("the sum of even numbers: "+sumeven);
System.out.println("the sum of odd numbers: "+sumodd);
System.out.println("the number of integers divided by 2 and 5: "+div5and2);
}
}
}
}
This is basic boolean algebra.
The 'opposite' of or is and, so if you want to stop when
"even >= 50 or odd >= 49"
you have to continue on the opposite, which is
"even < 50 and odd < 49".
while(sumeven<50||sumodd<49 ) means the program will run when sumeven<50 or sumodd<49, which means it will exit when sumeven>=50 and sumodd>=49.
When you negate a statement, >= becomes < and <= becomes >. Similarly, AND becomes OR and OR becomes AND. Here, your stopping condition is even >= 50 OR odd >= 49, the negation of this (which is what is required to continue) is even<50 AND odd<49.
You want the program to end when " the sum of even is >= 50 or the sum of odd is >= 49."
So, need something like (in psuedo code):
while (Not( the sum of even is >= 50 or the sum of odd is >= 49))
De Morgan's laws tell us we need to not each part to remove the brackets and switch between and and or:
while (Not( the sum of even is >= 50) and Not( or the sum of odd is >= 49))
Let's try some examples.
If the even sum is 50 and the odd sum is 40, you want to stop.
If you check
while (sumeven < 50 || sumodd < 49 )
you will keep going since sumeven < 50 is false, but sumodd < 49 is true.
Checking both parts:
while (evensum <= 50 && oddsum<=49)
works.
while(sumeven<50||sumodd<49 )
In this case, the program did not end if sumeven<50 OR sumodd<49. That is, the program will end when sumeven>=50 AND sumodd>=50.
Boolean logic 101:
!(A || B) == !A && !B note the &&.
Essentially if you are looking at a state where either A or B and want to take the compliment of that you must code it as not either A or B which is obviously neither A nor B or not A and not B.
AIM - The program will end when the sum of even is >= 50 or the sum of odd is >= 49.
Therefore, while (sumeven < 50 || sumodd < 49 ) won't work as the program will end when the sum of even is < 50 or the sum of odd is < 49 which is not the expected behavior.
Therefore, we must loop till
The sum of even is less than or equal to 50
The sum of odd is less than or equal to 49
The overall set of conditions should only be true if all conditions are true therefore we use && operator with the 2 conditions.

Less then or equal to Else IF Java stuck

This program enters in a temperature and based on the temperature a message is outputted. My program is getting stuck tempOutside <= 50 message.. When I enter -10 the output is "Time to turn on the heat". I cannot use && as this is an assignment questions and we have not used this concept.
if (tempOutside > 50)
System.out.println("Enjoy the weather");
else if (tempOutside <= 50)
System.out.println("Time to turn on the heat");
else if (tempOutside <= 30)
System.out.println("Check the gas in you car before leaving");
else if (tempOutside <= -10)
System.out.println("BUNDLE UP it's \"COLD\" outside ");
else
1) if-else must be in numerical order (hi to low)
2) Default must be coded
3) Repeat the code, but reverse the order(low to hi)
All ints are either > 50 or <= 50. The first two conditions match everything.
Change the second condition to
> 30
And the third condition to
> -10
Etc.
it would have been more clear if you could have mentioned your exact question directly and then your implementation as it looks like there could be a misunderstanding of the question here.
But I think perhaps this is what is being asked here??
if (tempOutside > 50)
{
System.out.println("Enjoy the weather");
}
else if (tempOutside <= 50)
{
if(tempOutside <= 30)
{
if(tempOutside <= -10)
{
System.out.println("BUNDLE UP it's \"COLD\" outside ");
}
else {
System.out.println("Check the gas in you car before leaving");
}
}
else
{
//when the temp is between 30 and 50
System.out.println("Time to turn on the heat");
}
}

java while loop won't print the text after a the stopping condition [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I just started studying Java and I'm required to use while to decided how many players can be goalkeepers based on their number. The loop is supposed to stop after the user entered 0 and print the counted number of players that can be goalkeepers.
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
count++;
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
From the question it is difficult to understand what it is you are trying to achieve. However, we can try to help you understand the code as it is written.
The while loop is currently written as:
while ((num != 0) && (num < 31) && (num%2==0) || (num%3==0))
This could be rewritten as the following and it would not make any difference:
while (num != 0 && num < 31 && num%2==0 || num%3==0)
The additional parenthesis that you included are not required.
In Java the operator precedence is && before ||. This means that the && operators will be evaluated first, followed by the ||. Therefore, the above statement could therefore be rewritten as the following and it would not make any difference:
while ((num != 0 && num < 31 && num%2==0) || num%3==0)
However, it may make the code a little easier to understand.
So when the code executes the following occurs:
The count variable is initialised to 0.
A value is retrieved and stored in the variable num. Lets say that this value is 10.
The while statement is evaluated for the first time:
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
As these all evaluate to true, the OR part (num%3==0) is not evaluated as it is not neccessary. See short circuit evaluation (http://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf).
The count is incremented to 1.
The loop executes again for the second time. num is still 10.
num != 0 is true as 10 != 0.
num < 31 is true as 10 is less than 31.
num%2==0 is true as 10 divided by 2 is 5 and leaves a remainder of 0.
The count is incremented to 2.
And so on... in an infinite loop.
If the variable num was instead set to 9. The loop would evaluate as follows:
num != 0 is true as 9 != 0.
num < 31 is true as 9 is less than 31.
num%2==0 is false as 9 divided by 2 is 4 and leaves a remainder of 1.
Therefore, now the || part is evaluted:
num%3==0 is true as 9 divided by 3 is 3 and leaves a remainder of 0.
Again, this would result in an infinite loop.
If the variable num was instead 0:
num != 0 is false
As the first num!=0 is false, the num<31 and num%2==0 parts are not evaluated as their results would not make any difference.
The num%3==0 is then evaluated:
num%3==0 is true as 0 divided by 3 leaves a remainder of 0.
Again, this would result in an infinite loop.
I hope that this may help to clarify your understanding and allow you to correct the code appropriately.
how many players' numbers do you have to input?
you have a while loop that depends on num value, but you never change the num value. that will end up in endless loop...
if you have more players, create a for loop to enter the numbers, store the numbers in an array or an arraylist and if you use the while loop, use it so that it depends on a value that you change inside the loop. otherwise it will loop forever.
do{
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}while(num!=0);
your code with this should look like this:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
int count = 0;
do {
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
} while (num != 0);
System.out.println(count + " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it
// won't
// print and keeps asking the user to enter a number.
}
If you can't use a do-while-loop as Ubica suggested, then you need to work your way around it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num=2; // you need to initialize num with a value, that allows you to go inside the while loop at least once
int count = 0;
while((num != 0) && (num < 31) && (num % 2 == 0) || (num % 3 == 0)) {
System.out.println("Enter the players' numbers");
num = input.nextInt(); // user input is here inside the loop
count++; // your count will count every valid input + the user input that ends the loop
}
count--; // if your user entered 0 to exit the loop, count would have still incremented, so you need do subtract one again
System.out.println(count + " players can be goalkeepers.\n");
}
As I commented in the code, first you initialize num with a dummy value, that allows you to enter the loop at least once. Then you listen to the users input and count the loop iterations. But since the loop will execute at least once (even though your user might enter 0 right away to exit the loop) your count would be one higher than the actual number of valid inputs. So you have to subtract that 1 from your count again.
EDIT
I forgot to mention: your loop will not stop when the user enters 0 because
(num % 3 == 0) // is true with num=0
so when the user enters 0 the while condition will evaluate like this:
while( false && true && true || true )
while( false || true )
while( true )
The bracketing for the loop should fix this problem.
You need braces surrounding your while loop block. As a general rule, it is best to overuse braces rather than under-use them.
Your code should look like:
package q3_201303719;
import java.util.Scanner;
public class Q3_201303719 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int num; int count=0;
System.out.println("Enter the players' numbers");
num = input.nextInt();
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
count++;
}
// The braces added above are required for the while loop and will keep your program
// from not outputting your results.
System.out.println(count+ " players can be goalkeepers.\n");
}
}
Best of luck and happy coding. :)
Your code isn't making sense.
1st : The While loop is not modifying the "num" value, resulting in
infinite loop if entered.
2nd : What is the code supposed to do? It is really hard to tell from what you show.
I think placing while loop upper could help you, but still code makes no much sense
public class Q3_201303719 {
public static void main(String[] args) {
int num = 0; int count=0;
while((num != 0) && (num < 31)&& (num%2==0)|| (num%3==0)) {
Scanner input = new Scanner (System.in);
System.out.println("Enter the players' numbers");
num = input.nextInt();
count++;
}
System.out.println(count+ " players can be goalkeepers.\n");
// Above line should be printed once the user enter 0, but in my case it won't
// print and keeps asking the user to enter a number.
}
}
Edit :
This problem occurred because you didn't follow a really simple rule : think before coding.
For this exercise you need to think about what your code should be doing, and then write the code for it. Coding is just a language, if you know what you want to write then it is easier. Here you obviously don't really know what you wanna do, and as you are new with development it was likely that you get stucked

If statement not working, skipping over to else

My "if" statement doesnt seem to be working, whatever I put in always seems to default to my "else" statement. Such as if I put in the integer "1" or "2", which have "if" statements associated with them, it still defaults to "else". Any help would be appreciated :)
String number = JOptionPane.showInputDialog("Would you like a custom loop count or an infinite? 1. Custom 2. Infinite"); //test choice
n = Integer.parseInt(number);
while (n < 0 || n > 2) {
if (n == 1) {
String number2 = JOptionPane.showInputDialog("How many times would you like to loop?");
integer = Integer.parseInt(number2);
while (integer < 0) {
while (x < integer) {
g.drawString("hi", 200, y);
x += 1;
y = y + 40; //test
}//end while
}
}//end if
else if (n == 2) {
while (1 == 1);
}//end if
else;
}
g.drawString("Please pick a valid choice", 200, 200);
If the block after
while (n<0 || n>2)
is executed, you know that n is either < 0 or > 2. Therefore it can't be equal to 1 or 2 and the else block is executed, which happens to be empty because it is followed by a ;.
That's not mentioning the few weird statements found in your code ;-)
ps: I have edited your post to add proper indentation to your code and include { and }. It might look a little clearer now.
else;
That's very wrong.
You don't have a else statement, it means the following line of code is executed.
This line is very bad too :
while (1==1);
Please indent following the norms and remove the unwanted ';'.

Categories