While loop not looping after script finishes - java

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

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

Need Assistance counting even and odd integers

Ok so I am reviewing for an exam in Java, and one of the problems asks us:
We wish to develop a program that will count the number of even and odd integers in a set ("even" meaning divisible by 2, "odd" meaning not divisible by 2). We will use zero as an indicator that the set has been completely entered, and this zero should not be counted as part of the set. Ask the user for a sequence of integers, terminated by zero. Output the number even integers and the number of odd integers.
When I run my code, for some reason the first variable is ALWAYS counted as even, regardless what the integer is. I can't for the life of me figure out why. Example: I type 23, 22, 25. It says 2 even 1 odd. However, if I type it 22, 23, 25 it says 1 even 2 odd.
Here is my Code:
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while(x != 0) {
x = IO.readInt();
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}
}
The issue is that you always ignore the first number and count the terminating 0 as even which gives an impression that first number is always counted as even.
You can fix this by reordering your while loop as
while(x != 0) {
// check odd-even first
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
// then read next int
x = IO.readInt();
}
You are overwriting the first input inside the while. It's better if you use a do while for this.
System.out.println("Enter Numbers");
// x = IO.readInt(); => remove this line
int even = 0;
int odd = 0;
while ((x = IO.readInt()) != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
EDIT: code edited to fix what #jschultz410 point out.
I think your issue might stem from the fact that the first number seems to be being skipped. You are putting it into x and then overwriting it immediately without looking at it. Try using a do-while loop instead, and putting the x = IO.readInt() at the end.
The first number entered is never evaluated:
int x = IO.readInt();
Then when the loop is entered it is overridden before evaluated:
while(x != 0) {
x = IO.readInt();
...
}
One solution is to move the reading to the end of the loop:
while(x != 0) {
...
x = IO.readInt();
}
There are a couple issues here. First, your very first value is being consumed, but it is not being used in your while loop. Also, you count your last value, which is 0. Reading the value last helps to solve that problem.
public class Problem4_Exam1Practice {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
int x = IO.readInt();
int even = 0;
int odd = 0;
while (x != 0) {
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
x = IO.readInt();
}
System.out.println(even + " even " + odd + " odd ");
}
}
Thanks everyone for the help! As for scanners we use an IO module provided to us, so we can't use scanners "YET".
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("Enter Numbers");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
int even = 0;
int odd = 0;
while(true) {
String s1 = bufferRead.readLine();
int x = Integer.parseInt(s1);
if(x==0)
break;
if (x % 2 == 0) {
even = even + 1 ;
}else{
odd = odd + 1 ;
}
}
System.out.println(even + " even " + odd + " odd ");
}

How Do I exit a loop and afterwards print Text

I've been trying to simulate somehting like the lottery.
I told java to run the while loop until the variable playCount equals 1000. Here is my code:
package problemset.leveltwo;
import java.util.*;
public class PlaySimLoop {
public static void main(String[] args) {
Random random = new Random();
int High = 100;
int Low = 10;
int playCount = 0;
int winCount = 0;
int loseCount = 0;
while (playCount > 1000) {
int yourNumber = random.nextInt(High - Low) + Low;
int winningNumber = random.nextInt(High - Low) + Low;
if (yourNumber == winningNumber) {
winCount = (winCount + 1);
}
if (yourNumber != winningNumber) {
loseCount = (loseCount + 1);
}
playCount = (playCount + 1);
if (playCount == 1000) {
break;
}
System.out.println("You Won " + winCount + " Times");
System.out.println("You Lost" + loseCount + " Times");
}
}
}
After I run the program it prints no information or statistics in the console of java eclipse. It says " PlaySimLoop (java application)" followed by a route to where it is saved on my computer.
Help is appreciated!
Tyler
Your loop condition is wrong
while (playCount > 1000) {
Will run while the variable is GREATER than 1000. But it starts at being 0... so the loop will never run. You probably want:
while (playCount < 1000) {
Which will run while the variable is less than 1000.
Furthermore, this blurb:
if (playCount == 1000) {
break;
}
Is unneccessary. The loop condition as defined in this answer will automatically stop after 999. Meaning this condition could never be true if you simply increment the counter by 1 each time as you're doing.
You might want to move the System.out.println out of the while loop.
someNumber = (someNumber + 1) can be written as someNumber += 1 or using the postfix increment operator: someNumber++. Instead of using another if condition you can use an else block.
if (yourNumber == winningNumber) {
winCount++;
} else {
loseCount++;
}
loseCount could also be calculated at the end from playCount - winCount.

Simulate the tossing of a coin three times and print out the percentage of cases in which one gets three tails

Attached is the problem: http://puu.sh/42QtI/ea955e5bef.png
In terms of code, this is what I have so far
The question asks to "calculate the simulated percentage of three tails," which is the part I am stuck on. Could someone give me some insight on what to progress next?
public static boolean isThreeTails(){
Random rand = new Random();
int numberOfTosses = 3;
int numberOfHeads = 0;
int numberOfTails = 0;
for(int i = 1; i <= numberOfTosses; i++){
int value = rand.nextInt(2);
if(value == 0){
numberOfTails++;
}else{
numberOfHeads++;
}
}
if(numberOfTails == 3){
return true;
}
else{
return false;
}
}
double numTosses = 1000000; //choose whatever here
double threeTails = 0;
for(int i =0; i < numTosses; i++){
if(isThreeTails()){
threeTails++;
}
}
System.out.println("Theoretical probability of 3 Tails: " + (double) 1/8);
System.out.println("Actual results for " + numTosses + " tosses = " + threeTails/numTosses);
EDIT: Here, I am creating a counter for when there are triple tails. It would increment the numberOfTripleTails counter. If it rolls a "H", the numberOfTails would simply go back to zero. However, my code seems to only give '3' as an answer.
EDIT 2: Done!
Alright - you've run your simulation and you have your value for number of heads and number of tails. Now you'll need to run a few more.
Each time you run a simulation, increment a variable that tracks the total amount of times you've run it. If number of tails comes out to three, you increment another variable: let's call it successes.
The outcome to the problem are the successes over the total times the simulation was run.
The method that you have already written simulates three tosses. I've modified that method so that it is now a callable function isThreeTails()
public static boolean isThreeTails(){
Random rand = new Random();
int numberOfTosses = 3;
int numberOfHeads = 0;
int numberOfTails = 0;
for(int i = 1; i <= numberOfTosses; i++){
int value = rand.nextInt(2);
if(value == 0){
numberOfTails++;
}else{
numberOfHeads++;
}
}
if(numberOfTails == 3){
return true;
}
else{
return false;
}
}
Now you will want to call this method from the main method of ThreeTosses.java
double numTosses = 100; //choose whatever here
double threeTails = 0;
for(int i =0; i < numTosses; i++){
if(isThreeTails()){
threeTails++;
}
}
System.out.println("Theoretical probability of 3 Tails: " + (double) 1/8);
System.out.println("Actual results for " + numTosses + " tosses = " + threeTails/numTosses);
The question is saying, "in theory, you should get 3 tails 1/8th of the time". Now it's saying, "OK, you know the theory, now actually do this on a computer and see what you really get."
What you want to do is run this code a bunch of times and keep track of the number of times you got 3 tails. Take that number and divide it by the total number of times you ran the code. That should be the simulated percentage.
Just in case you can't tell, I'm saying to do this in code, not by manually running your current code over and over again. Here's some pseudo code:
threeTailsCount = 0
for i = 0; i < 1000; i++
if currentCodeReturns3Tails
threeTailsCount += 1;
print (threeTailsCount / 1000)

Loop with Dice rolling program, previous roll and double check

A fairly trivial problem to most I am sure but I can't quite work out how I'm meant to get the previous dice integer to remain the same as the previous roll of die in the program. I think the code is fairly self explanatory and this is such a trivial program I'm kicking myself for not being able to get my head around it.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int min = 1;
int max = 6;
int loop = 0;
int diceRollOne = 0;
int diceRollTwo = 0;
int diceTotal = 0;
int prevDiceTotal = 0;
while (loop < 15000) {
loop++;
diceRollOne = rand.nextInt(max - min + 1) + min;
diceRollTwo = rand.nextInt(max - min + 1) + min;
diceTotal = diceRollOne + diceRollTwo;
System.out.println("Dice Roll 1: " + diceRollOne);
System.out.println("Dice Roll 2: " + diceRollTwo);
System.out.println("Dice Total: " + diceTotal);
System.out.println("previous total: " + prevDiceTotal);
prevDiceTotal = diceTotal;
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
}
}
}
The basic idea being 15,000 simulations. Roll two dice. If you roll a double quit. If you roll the same sum in the current roll as the sum of the previous roll then quit. I've tried debugging by printing out the previous dice total but it defaults to zero every time.
You just want to move the prevDiceTotal = diceTotal; to after your if statement.
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
prevDiceTotal = diceTotal;
You have the following:
prevDiceTotal = diceTotal;
if(diceRollOne == diceRollTwo || diceTotal == prevDiceTotal){
As it's written now it guarantees if-expression to be True.
Move the assignment after your if block.
This is where a good IDE can help you. Here is what IntelliJ IDEA (which has a free Community Edition) shows for your code. Note the highlighting of the if() statement along with a description of the problem.
As others have said, move the assignment of prevDiceTotal after the if() block to solve the problem.

Categories