Beginner Java Programming - Rolling 2 Dice Game - java

I'm trying to create a java program for my class that throws 3 dice. The player rolls the dice and earns a profit in dollars based on the three values obtained. In particular, the profit is equal to the number of even values multiplied by the sum of those values, plus the number of odd values multiplied by the sum of those values.
For example, if the player rolls 4, 5, and 2 we calculate:
2 x 6 (two even values summing to 6)
And
1 x 5 (one odd value summing to 5).
So the profit is 12 + 5 = $17.
Here is what I have so far -
import java.util.Scanner;
public class Maiorca_Hw2
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter Values of Dice 1");
d1 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 2");
d2 = keyboard.nextDouble();
System.out.println("Enter Values of Dice 3");
d3 = keyboard.nextDouble();
double numbers = 1,2,3,4,5,6;
double profit, dice, d1, d2, d3, oddsum, evensum;
if (d1 == 1 || d1 == 3 || d1 == 5)
oddsum =

I personally think that the program should be done in a different way and you should also use clases.
I hope this little code helps you!
First of all we must create a class called Dice, where we will set the behaviour of a dice and the interactions allowed.
You say that the player rolls, so there must be a random event, I think.
//CODE:
import java.util.Random;
public class Dice {
private final int SIDES;
//Constructor for a dice
public Dice(int sides){
//Establishes the number of sides of the dice we're using.
SIDES = sides;
}
//Methods:
public int roll(){
Random rnd = new Random();
return rnd.nextInt(SIDES) + 1;
}
}
After that, in the main class, we put it to the test.
The why of everything is in the comments
//CODE:
public class MainClass {
public static void main(String[] args) {
int moneyEarned = 0;
//We generate 3 dices with 6 sides each.
Dice d1 = new Dice(6);
Dice d2 = new Dice(6);
Dice d3 = new Dice(6);
// Then we start the simulation:
int res1, res2, res3;
res1 = d1.roll();
res2 = d2.roll();
res3 = d3.roll();
//Show results:
System.out.println("Roll results: dice 1 = " + res1 +
"; dice 2 = " + res2 + "; dice 3 = " + res3);
//We obtain the money the player must earn:
//An even number modulo 2 can only be either 1 or 0 so the same number + 1 will
//switch from 0 to 1 and the opposite thing.
//With this number we can choose which numbers we want to sum:
int oddNumbersPoints = ((res1 * (res1%2))+(res2 * (res2 % 2))+( res3 * (res3 % 2)));
int evenNumbersPoints = ((res1 * ((res1 + 1) %2)) + (res2 * ((res2+1) % 2))+( res3 * ((res3+1) % 2)));
moneyEarned = (evenNumbersPoints * 2) + oddNumbersPoints;
//Finally display the final result:
System.out.println("Even Numbers Points: " + evenNumbersPoints);
System.out.println("Odd Numbers Points: " + oddNumbersPoints);
System.out.println("Congratulations, you just earned: " + moneyEarned + "$");
}
}
/////
Finally you can change the main class to change the number of dices, the scores, so on...
(Add '}' and the main class head)

What you can do declaring primitive types, in this case double, is:
double profit = 0, dice = 2, d2 = 3;
To declare an array of doubles:
double[] numbers = {1,2,3,4,5,6};

Related

Dice continuous sum game Java

I'm new to programming and trying to make a dice game. The game consists of three dice and involves the sum of 12 (on any number of dice) in each round. Each dice can only be rolled once per round.
In each round, the player must be able to choose between: 1 to roll the dice 1, 2 to roll the dice 2, 3 to roll the dice 3, q to exit the game. The program must randomly find a value on the selected dice and then calculate the score. The program should also present the number of wins and the number of rounds lost. The program should continue until the user chooses to cancel the game. Regardless of the number of dice, and the definition of loss is a sum exceeding 12 after all three dice have been rolled. If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round.
So currently my code works for 1 round, the problem begins when the second round begins. The new dice rolls are just the input I give it, and not a random value (1-6).
How can I make this work?
import java.util.Scanner;
import java.util.Random;
public class Main{
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int rounds;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkRounds();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
}
}
}
When you are going for the next round, the method tärningsKast() is only going to work again and again once each round passes if the dice is not thrown.
Meaning that once a round finishes and you are going to start another round, you have to set that the dices are not thrown, since the round is going to start right after.
The solution I found is to set the dice1Thrown, dice2Thrown and dice3Thrown to false on the if statement that prints that the next round is starting.
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
After that the game seems to be working fine.
The steps I made to find that it, were:
Set a break point to debug the line that prints "Next round".
Once the debugger reachs that line, set a break point in the first line of the method tärningsKast(), then check that in each check of the if, else if and etc. the diceNThrown variables are all still setted to true, so none of the conditions will match.
Regarding the question:
"You mean, if you wanted to stop the game in the round 2 ?"
"Yeah exactly like that"
First I'd use you checkRounds() method to check if it were to stop the game, meaning if the user already played two rounds.
Second I would move the logic that move to the next round to a method that checks attemps, intead of rounds, since we will move to the next round every time the user already had three attempts.
And finally before moving to the next round I would be increasing the number of rounds, and right after checking if the number of rounds if the expected number of rounds to stop, that way you can play the game with the limit of rounds you desire to.
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int attempts;
// keeping track of the number of rounds
static int rounds = 0;
// desired number of rounds to play
static final int LIMIT_OF_ROUNDS = 5;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkAttempts();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkAttempts(){
attempts++;
if(attempts == 3)
{
rounds++;
checkRounds(rounds);
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
attempts = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
}
static void checkRounds(int rounds) {
if (rounds == LIMIT_OF_ROUNDS) {
tärningsKast('q');
}
}

Java percentage calculation based on multiple inputs

I'm little bit confused how to calculate percentage based on input values (eg: pick for team)
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
}
System.out.println(team1);
System.out.println(team2);
System.out.println(draw);
int total = team1 + team2 + draw;
System.out.println(total);
This will print individually and total.
l want to print for example if all values are picked 2 times from input:
"Team 1 = 33.3%, Team 2 = 33.3%, draw = 33.3%" and so one for different type of picks. Thanks
You are almost there. Now, all you just need is a counter to count the iterations and finally divide the score of team1, team2 and draw by the value of the counter after multiplying them with 100.0 to get the percentage score.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
int count = -1;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
count++;
}
System.out.printf("Percentage score of team1: %.1f%n", (team1 * 100.0 / count));
System.out.printf("Percentage score of team2: %.1f%n", (team2 * 100.0 / count));
System.out.printf("Percentage score of draw: %.1f%n", (draw * 100.0 / count));
}
}
A sample run:
1 for Team one, 2 for Team two, 3 for draw, 9 for quit
1
2
3
3
2
1
9
Percentage score of team1: 33.3
Percentage score of team2: 33.3
Percentage score of draw: 33.3
To get the percentage of each price you have to do:
int persentageteam1 = team1*100/(team1+team2+team3);
and the same for the others...
Explanation:
What you do here is divide the price of which you want to find the persentage with the sum of the rest of the other and do this x100
A percentage of a number is calculated basing on the following principle (or at least as it is taught is my school) :
Say, you need to figure out a number percent ratio of another one, let it be firstNumber and secondNumber. Then, firstNumber=100% and secondNumber=x. From that we get the proportion: firstNumber/secondNumber = 100%/x, consequently, x=(secondNumber*100)/firstNumber. That is, in your case, the firstNumber is the pick summary of all teams and the secondNumber - the team which percentage you want to determine. For example
//your code
int pickSummary=team1+team2+team3+draw;
int team1Percentage=team1*100/pickSummary;
System.out.println(team1Percentage);
//and so on

Balut dice game Java

I'm making a game for an extra assignment for my college and I have to create a dice game known as "balut" I'm having some issues with assigning values to an array, and having the dice values stored within this array.
I'm in week 9 of 11 of my course we've covered arrays and methods however this is a new concept for me. The goal is as follows:
Balut = all five dice have the same number.
Straight = a total of 15 Or 20.
Sixes = 1 or more sixes.
Fives = 1 or more fives.
Fours = 1 or more fours.
10 rounds.
Total scoring of categories.
total of scores.
If no category is met "none" is printed.
I've put at least 14 hours into this and it was intended to be a 6 to 8 hour program and I still am struggling, questioning if I have the intelligence for the course and am hoping someone here can explain what I'm doing wrong or even what I should be studying.
I've tried creating a single array and assigning all dice values to this array, I run into the problem of when it comes to comparing the values I don't know how to do dice 1 == dice 2 == dice 3 etc.
I've then attempted to make 5 arrays 1 for each dice and use the compare array method which again I can only seem to get it to compare 2 arrays or variables I can't get it to compare all 5 like I'm attempting.
public static void main(String[] args) {
int[] Dicearraytotal1 = new int[10];
int[] Dicearraytotal2 = new int[10];
int[] Dicearraytotal3 = new int[10];
int[] Dicearraytotal4 = new int[10];
int[] Dicearraytotal5 = new int[10];
for (int i = 0; i < Dicearraytotal1.length; i++) {
Integer dice1 = (int) (Math.random() * 6 + 1);
Integer dice1val = dice1;
Integer dice2 = (int) (Math.random() * 6 + 1);
Integer dice2val = dice2;
Integer dice3 = (int) (Math.random() * 6 + 1);
Integer dice3val = dice3;
Integer dice4 = (int) (Math.random() * 6 + 1);
Integer dice4val = dice4;
Integer dice5 = (int) (Math.random() * 6 + 1);
Integer dice5val = dice5;
Dicearraytotal1[i] = (dice1val);
Dicearraytotal2[i] = (dice2val);
Dicearraytotal3[i] = (dice3val);
Dicearraytotal4[i] = (dice4val);
Dicearraytotal5[i] = (dice5val);
Integer total = (dice1val+dice2val+dice3val+dice4val+dice5val);
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(Dicearraytotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(Dicearraytotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(Dicearraytotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(Dicearraytotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(Dicearraytotal5));
System.out.println("Total: " + total);
You are missing an end bracket to stop the for loop, so I assume you were attempting to print the arrays each iteration of the loop. I cleaned up your code a lot and you should take note on some of the changes in order to organize your code better which will make it easier to understand.
public static void main(String[] args) {
int[] diceArrayTotal1 = new int[10];
int[] diceArrayTotal2 = new int[10];
int[] diceArrayTotal3 = new int[10];
int[] diceArrayTotal4 = new int[10];
int[] diceArrayTotal5 = new int[10];
int[] totals = new int[10];
for (int i = 0; i < diceArrayTotal1.length; i++) {
diceArrayTotal1[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal2[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal3[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal4[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal5[i] = (int) (Math.random() * 6 + 1);
totals[i] = (diceArrayTotal1[i] + diceArrayTotal2[i] + diceArrayTotal3[i] + diceArrayTotal4[i] + diceArrayTotal5[i]);
}
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(diceArrayTotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(diceArrayTotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(diceArrayTotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(diceArrayTotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(diceArrayTotal5));
System.out.println("Totals: " + Arrays.toString(totals));
}
Additionally I added a totals array that keeps the total for each index instead of printing it every loop like you were doing. You did not add your compare code, so I cannot assist you with that. Let me know if you need any clarification on any changes. I ran this code and it successfully generated the arrays you need and the totals.
public static void main(String[] args) {
int[] results = new int[6]; // This array will hold the number of time each dice was rolled, so for example results[0] is how many 1 s you have results[5] is how many 6 you have
Random random = new Random();
for (int i = 0; i < 5; i++) { // roll the dice 5 times
results[random.nextInt(6)]++; //increase the counter of the appropriate value
}
boolean balut = false;
for (int i = 0; i < 6; i++) {
System.out.println("Number of " + (i+1) + ": " + results[i]);
if (results[i] == 5) {
balut = true;
}
}
if (balut) {
System.out.println("Balut!");
}
}
Here I implemented only the check for the Balut, but the main point is how I am couting the dices results. Hope it helps.

D&D Character stat roller (Java)

So I am very new to the Java language and I'm attempting to put together a dice roller of sorts for character stat generation for D&D (Dungeons and Dragons).
What I want the program to do is roll x number of D6, x amount of times. X is to be input by the user. I also need the program to ask if it is to re-roll a result of 1 on a D6 roll. Plus, the program must only keep the highest 3 numbers of the rolled dice. It then needs to output the results of each grouping of dice rolls, instead of totaling them all together.
So an example would be: I want 4 D6 rolled 6 times, and re-roll 1's.
The program output would be something along the lines of:
Your results are:
10
12
13
15
17
11.
I'm trying to write this with 3 classes, though I know it doesn't need to have 3 classes to operate. The additional classes are more of a requirement from a project standpoint.
I've managed to code what is necessary to roll a single dice, but as I said I'm very new and have almost zero idea on where to go with this.
The code I have so far is:
//Scanner is implemented in preparation for user input as more coding is
//added
import java.util.Scanner;
public class RollDie {
public static void main(String[] args) {
int SIDES = 6; // how many sides on the die?
// roll should be 1 through SIDES
int roll = (int) (Math.random() * SIDES) + 1;
// print result
System.out.println(roll);
}
}
A one-class solution with freindly user input could look like this:
private final static int SIDES = 6;
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner (System.in);
System.out.println("Number of dice?");
final int dice = scanner.nextInt();
System.out.println("Number of rolls?");
final int rolls = scanner.nextInt();
System.out.println("Reroll result 1? Enter y for yes");
final boolean reroll = scanner.next().equals("y");
for (int r = 0; r < rolls; r++) {
int allDice = 0;
for (int d = 0; d < dice; d++) {
int roll = (int) (Math.random() * SIDES) + 1;
while (reroll && roll == 1) {
roll = (int) (Math.random() * SIDES) + 1;
}
allDice += roll;
}
System.out.println(allDice);
}
}

How to calculate circumference with random numbers?

I need to print the circumference with Math.random() * Math.Pi; but i'm doing something wrong or missing something. Each random generated number equals the radius of the circle. My idea was to calculate Pi in the getRandomNumberInRange method but when I do, I get error:
Bad operand for type double
import java.util.Random;
import java.util.Scanner;
final static double PI = 3.141592564;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
//ask the player to enter a number less than or equal to 18 and higher to 9.
System.out.println(" Please enter a number less than or equal to 18 and above 9: ");
int random = sc.nextInt ();
//send error message if bad input
if (random < 9 || random > 18) {
System.out.println(" Error. Unauthorized entry . You need to enter a number less than or equal to 18 and above 9 ");
} else
//If the answer is yes , generate nine different random numbers from 0.
for (int i = 0; i < 9; i++) {
double surface = PI * (random * 2);
System.out.println(getRandomNumberInRange(9, 18) + " : " + " The circumference is : " + surface );
}}
The method called:
private static int getRandomNumberInRange(int min, int max) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
You call getRandomNumberInRange() in the for loop, but don't assign it to anything, or use it.
This is probably closer to what you want:
for (int i = 0; i < 9; i++) {
int r2 = getRandomNumberInRange(9, 18);
double surface = PI * (r2 * 2);
System.out.println(r2 + " : " + " The circumference is : " + surface);
}

Categories

Resources