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.
Related
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;
}
I'm attempting my first project in Java after learning the basics, so I apologize for what is likely a complete beginner question. I have been searching all afternoon for assistance, and my code is starting to look messy and broken.
I am attempting to create a dice roller that rolls a number of d10s, then proceeds to check how many are 7's or above and count/display them as successes. If none of the rolls are a success, I want it to display "Botch".
After some research, I found creating an ArrayList and going from there was (what seems to me as) the best option. But I've been stuck for some time now, with different errors and issues coming up, and each time I take one down, the code gets more confusing and my goal seems farther away. My buddy said "welcome to programming" and suggested I ask the community.
Here is what I'm working with:
import java.util.Scanner;
import java.util.ArrayList;
public class RollDie {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
String numberOfDice;
// User input for number of dice to roll
System.out.print("How many dice? ");
numberOfDice = userInput.next();
System.out.println("Rolling " + numberOfDice + " dice!");
userInput.close();
Integer roll = 0;
int dice = Integer.parseInt(numberOfDice);
int sides = 10; // # of die sides
ArrayList<Integer> sux = new ArrayList<Integer>(); // Store results of roll
// print result
for(int d=0; d < dice; d++) {
// roll should be 1 through sides
roll = (int) (Math.random() * sides) + 1;
sux.add(roll);
}
System.out.println(sux);
// Count successes and print or check for botch
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) {
s++;
System.out.println(s + " successes!");
} else {
System.out.println("BOTCH!");
break;
}
}
}
}
Everything after it prints the sux ArrayList is a mess. I know that the for loop is wrong, I just don't know how to make it right. The variable s seems out of place... Any help would be appreciated, and let me know if this post is against standards for the community in anyway. Thanks!
EDIT: To clarify my ramblings, my question is: how to check if the numbers that are being added to the ArrayList after rolling are greater than or equal to 7 (or any number)?
As #Aomine suggestion earlier you need a flag which helps you to find rather if any dice is >=7 or no dice reach this condition.
// Count successes and print or check for botch
boolean isBotch=false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
//s++; //no need to use this counter here again
System.out.println((s+1) + " successes!"); // s+1 gives you right location
} else {
isBotch = true; //flag variable
}
}
if(!isBotch){
System.out.println("BOTCH!");
}
How about this?
System.out.println(sux);
// Count successes and print or check for botch
int gtNumber = 0;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
gtNumber++;
System.out.println(s + " successes!");
}
}
if(gtNumber == 0){
System.out.println("BOTCH!");
}
}
updated:
for(int s = 0; s < sux.size(); s++){
if(sux.get(roll) >= 7) { //here value of sux.get(roll) will be regardless to s. should be typo.
s++;// no need to change value of s, as it will be changed during for clause.
System.out.println(s + " successes!");
break;
} else {
System.out.println("BOTCH!");
}
should be
bool foundvalue = false;
for(int s = 0; s < sux.size(); s++){
if(sux.get(s) >= 7) {
System.out.println((s+1) + " successes!");
foundvalue = true;
break;
}
}
if (!foundvalue){
System.out.println("BOTCH!");
}
Calculate the Probability of winning (wins/ (wins + losses)) using 10,000 simulations in the game of craps. Here is the method for the game of craps:
public class CrapsGame {
public static void main(String[] args) {
int dice1 = (int)(Math.random()* 6) + 1;
int dice2 = (int)(Math.random()* 6) + 1;
int roll = dice1 + dice2;
System.out.println();
System.out.print("You rolled "+roll+". ");
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
}else{
System.out.println("Point is "+roll+"\n");
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
int roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
while(roll2 != 7){
if(roll == roll2){
System.out.println("You Win !");
break;
}else{
System.out.println("Point is "+roll+"\n");
}
dice1 = (int)(Math.random()* 6) + 1;
dice2 = (int)(Math.random()* 6) + 1;
roll2 = dice1 + dice2;
System.out.print("You rolled "+roll2+". ");
}
if(roll2 == 7){
System.out.println("You Lose !");
}
}
}
}
I don't think this should be difficult, I just need code to run 10,000 simulations and then also calculating the probability. Thank you :)
Would it be possible to have someone insert a working version of this
Putting a while or for loop outside of the logic and creating 2 counters (timesWinning, timesLosing). Incrementing each according, inside the existing code. After the loop runs 10.000 times, do the math as needed: wins/ (wins + losses)
thank you this is part of an assignment
And you should modify his code to this at the end:
System.out.println("Probability of winning: " + ((double)timesWon/(timesWon + timesLost)));
I got this as a result from my own:
You played: 10000.0, won: 5078, probability of winning : 0.5078
You played: 1.0E8, won: 50707214, probability of winning : 0.50707214
Your code has already all the logic needed. To repeat it as many times you want, there are different ways. They are known as loops. If you search on Google you will find for, while, do/while and some others (you have a while already inside the code).
For your question, the basic would be to repeat it 10,000 times the same things.
public class CrapsGame {
public static void main(String[] args) {
// Create some variables to control the times it won and times it lost
int timesWon = 0;
int timesLost = 0;
// Here we're saying it's gonna repeat 10000 times, incrementing 1 by 1
for(int i=0; i<10000; i++) {
// Here you will insert all the existing logic from your program
// In the existing code, increment the variables declared according
if(roll == 2 || roll == 3 || roll == 12){
System.out.println("You Lose !");
timesLost++;
}else if(roll == 7 || roll == 11){
System.out.println("You Win !");
timesWon++;
}else{
// Where you find it won, insert `timesWon++;`
// Where you find it lost, insert `timesLost++;`
}
}
// Here it exits the for loop (after 10000 times)
// Here's where you can calculate
System.out.println("Probability of winning: " + (timesWon/(timesWon + timesLost)));
}
}
This should be sufficient to get the desired result.
Hope it helps.
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.
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)