Java: While Loop and array incrementing - java

I want the program to keep incrementing the innings for each iteration of the loop.
When I run the program it's doing that, however it's showing me incorrect values.
For example:
You rolled...4
Your total for this innings so far is 6
The second line should be showing, "... so far is 4"
This is the code that I have at the moment:
import java.util.Random;
import javax.swing.*;
public class shortSix {
public static void main(String[] args) {
diceGame();
}//ENDS MAIN
public static void diceGame()
{
final int[] innings = new int[1];
innings[0] = 0;
Random dice = new Random();
int diceRoll = dice.nextInt(6) + 1;
while (diceRoll != 5)
{
System.out.println("You rolled..." + diceRoll);
diceRoll = dice.nextInt(6) + 1;
innings[0] =+ diceRoll;
System.out.println("Your total for this innings so far is " + innings[0]);
String userDeclare = JOptionPane.showInputDialog(null, "Do you wish to declare?");
if (userDeclare.equals("yes"))
{
System.exit(0);
}
}
}//ENDS diceGame
}//ENDS class shortSix

The problem is that you aren't updating the array record after the first roll. You've got int diceRoll = ..., then you assign random value to the variable again and add the score after the second roll. The first result is ignored. All you have to do is change
diceRoll = dice.nextInt(6) + 1;
innings[0] =+ diceRoll;
to
innings[0] =+ diceRoll;
diceRoll = dice.nextInt(6) + 1;

There are two problems:
=+ instead of += before the second println
Order of operations is strange. You first print the current value, then update it and only then increases counter and prints summary. Probably you wanna move diceRoll = dice... after the second println

You call
diceRoll = dice.nextInt(6) + 1;
before printing
System.out.println("Your total for this innings so far is " + innings[0]);
which causes making a new random number, and it is the problem.

Related

How to calculate the sum of values generated by a loop

I am an extreme beginner at this, so the answer might be obvious and staring me in the face. I need to add together three numbers generated by a loop. The numbers are random (btw 1 and 6) and taken from another method. I can't seem to figure out how to use any of the values generated by the loop once it terminates.
It's for a homework assignment where we're supposed to simulate a dice-rolling game, and part of the assignment is to add together three dice rolls in order to display the score. I assume I'm supposed to add together the three rolls in order to get the score, but I 1) don't know where to add them together (inside of the loop? outside of it, and how do I in that case retrieve the values from the loop?), and 2) don't even know if just saying that score = roll+roll+roll is the right way to go about it. I feel like have missed something somewhere.
int score = getScore();
System.out.println(score);
}
static int diceRoll () {
int range = (6-1) + 1;
double roll = Math.random() * range;
return (int)roll + 1;
}
public static int getScore () {
int score = 0;
int roll = 0;
int i = 1;
for (i=1; i<=3; i++) {
roll = diceRoll();
//I added this in order to make sure that the first part works
System.out.print(roll + " ");
}
score = roll+roll+roll;
return score;
In an ideal world this would display three random numbers between (and including) 1 and 6 (which it does), as well as the sum of these three numbers (e.g for 2, 4, 6, score would be 12).
It checks out sometimes, but most of the time it returns completely random numbers. I suspect that this is the completely wrong way of doing it, but I can't really think of what to do.
Code with comments
static void main(String[] args) {
int score = getScore();
System.out.println(score);
}
static int diceRoll() {
int min = 1;
int max = 6;
return ((int)(Math.random() * ((max - min) + 1)) + min);//it'll return values between 1 and 6
}
public static int getScore() {
int score = 0;
int roll = 0;
for (int i = 1; i <= 3; i++) {
roll = diceRoll();//you first need save the returned value
score = score + roll; //at this point you accumulate the returned values
System.out.print(roll + " ");
}
return score;
}

How to count a variable using a for loop?

I'm designing a program that simulates a game of dice. The code calculates the total points get each round and the player that wins each round.
I am trying to get the overall number of wins and the total points. I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
Round 1:
player 1 3 1 5 points: 9
player 2 2 6 6 points: 14
Winner is player 2
Round 2:
player 1 3 6 5 points: 14
player 2 2 3 2 points: 7
Winner is player 1
Round 3:
player 1 3 3 6 points: 12
player 2 5 4 6 points: 15
Winner is player 2
.
Total wins: player 1-->1/ player 2-->2
Total points: player 1-->35/ player 2-->36
Main class
import java.util.Scanner;
public class Game {
// ------------------- FIELDS ------------------------
// Create instance of Scanner class
public static Scanner input = new Scanner(System.in);
// variables
public static ThreeDiceScorer thrdiesc;
public static int diceArray [];
// ------------------ METHODS ------------------------
public static void main(String[] args) {
int rounds; // input by user
int players; // input by user
System.out.print("Please input number of rounds (grater or equal than 0) --> ");
rounds = input.nextInt();
System.out.print("\n");
System.out.print("Please input number of players (grater or equal than 2) --> ");
players = input.nextInt();
System.out.print("\n");
for (int r = 0; r < rounds; r++) { // loop for number of rounds
int max = 0;
int max_p = 0;
System.out.println("Round " + (r+1) + ": ");
for (int p = 0; p < players; p++) { //loop for players
int diceArray[] = new int[3];
for (int i = 0; i < diceArray.length; i++) { // loop for dice Array (data of Array)
diceArray [i] = 1 + (int)(6 * Math.random());
}
// Create new ThreeDice and calculator instances
thrdiesc = new ThreeDiceScorer(diceArray [0], diceArray [1], diceArray [2]);
//Calculate
thrdiesc.calcTotalPoints();
thrdiesc.printResult(p, r);
if (thrdiesc.total > max) {
max = thrdiesc.total;
max_p = p;
}
}
System.out.println("Winner is player " + (max_p + 1) + "\n");
}
System.out.println("Total wins: " );
System.out.println("Total points: " );
}//end Main Method
} // end Class
Calculation class
public class ThreeDiceScorer {
public static int total;
public int die1;
public int die2;
public int die3;
public ThreeDiceScorer(int s1, int s2, int s3) {
die1 = s1;
die2 = s2;
die3 = s3;
}
public void calcTotalPoints() {
int sumOfDice = die1 + die2 + die3;
total= sumOfDice;
}
public void printResult(int p, int r) {
System.out.println("player " + (p + 1) + " " + die1 + " " + die2 + " " + die3 + " " + "points: " + total);
}
}
I tried using a for loop in the main class but I wasn't sure how to implement it in this problem.
I would say, do one thing at a time. Test your implementation and once you confirmed that it is working, then move on. The sequential steps to reach your goal would be:
Steps
Implement dice rolling for one player first. (Can do it in a method)
Call the above implemented method for 2nd player's dice roll.
Decide winner
Once steps 1-3 were implemented correctly, enclose steps 1-3 within a loop (preferable a for-loop for this particular case)
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
Once steps 1-4 is tested and working fine. Implement the display of total score:
//Example:
int numOfRounds = 3; //can receive this from user input
for(int x=0; x<numOfRounds; x++){
rollDice(playerOne);
rollDice(playerTwo);
decideWinner(playerOne, playerTwo);
}
displayFinalScore();
Total score and total wins can be stored in a very simple Player class which looked like this:
public class Player{
private String name;
private int totalScore;
private int totalWins;
}
Dynamic Multi-player
I tried to keep the solution as short and simple as possible for your understanding. But if you want the program to dynamically take in n number of players. The same program flow still applies.
In step 4, you can do it as:
int numOfPlayers = 2; //can receive this from user input
ArrayList<Player> players = new ArrayList<Player>();
for(int x=0; x<numOfPlayers; x++)
numOfPlayers.add(new Player("Player " + (x+1)));
for(int x=0; x<numOfRounds; x++){
for(int y=0; y<players.size(); y++) //iterate through all players
rollDice(players.get(y));
decideWinner(players); //decide the winner from all the players
}
There are many ways to solve this, I would add two counters like int count = 0 and increment them: one every time there is a victory (for ex.: if(victory) { c++ })and the other through the expression count = count + points.
Remember to implement these ints at the beginning or the for loop will reset count1 and count2 to 0.

Java - Stuck in "for" loop

I am writing a java program that takes a number, x, as input from the user, sums all numbers from 1 to x (including x) that are divisible by 3, and displays the sum. it compiles without error but when I execute the program, it gets stuck in the loop and continues executing until I close the command prompt. I think the problem is inside the parenthesis after "for". I tried replacing the commands inside the loop with a simple
System.out.println("Hello");
and I got hundreds of Hello's streaming down the command prompt window. What am I doing wrong?
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number");
int x = keyboard.nextInt();
int i, total = 0;
for (i = 0; i <= x; i=+3)
{
total =+ i;
}
System.out.println("The sum is " + total);
}
Your =+ should be +=.
total =+ i; is the same as total = +i; which is the same as total = i;.
Your assignment is wrong. At the time being, you are simply assigning the counter to 3.
i += 3
You've done the same with your total variable as well. You can fix it in the same way:
total += i;
Wrong operator it is endlees loop. Use += not =+
i += 3
just fix when you increase the i and the total. Here is the class to compile and run :
import java.util.Scanner;
class keyboard {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a number");
int x = keyboard.nextInt();
int i, total = 0;
for (i = 0; i <= x; i+=3)
{
total += i;
}
System.out.println("The sum is " + total);
}
}

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