Reroll dices in yahtzee game - java

I´m trying to create a simple yahtzee game where an array is filled with 5 random numbers and where the player can choose to roll specific dices again. However I cant figure out how to write the method that is supposed to replace specific numbers in the array with new random numbers and return it. Any suggestions how to approach this?
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class YatzyGame {
private final Integer NBROFDICE = 5;
private final Integer DICEMAXVALUE = 6;
Random rnd = new Random();
Scanner keyboard = new Scanner(System.in);
public void startGame() {
int[] dice = new int[NBROFDICE];
rollDice(dice);
printDice(dice);
System.out.println("Do you want to reroll any dices? " + "Y/N");
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("y")) {
rerollDice(dice);
} else if (answer.equalsIgnoreCase("n")) {
calculateSum(dice);
} else {
System.out.println("Wrong command!");
}
}
public int[] rollDice(int[] dice) {
for (int i = 0; i < dice.length; i++) {
dice[i] = rnd.nextInt(DICEMAXVALUE) + 1;
}
return dice;
}
public int[] rerollDice(int[] dice) {
System.out.println("What dices do you want to reroll? Dices index are 0-4");
int diceToReroll = keyboard.nextInt();
// Replace the numbers at the index the user specifies with new random numbers and return the array.
}
public void printDice(int[] dices) {
System.out.println("Your dices show: " + Arrays.toString(dices));
}
public void calculateSum(int[] dices) {
int sum = 0;
for (int i : dices) {
sum += i;
}
if (sum == 30) {
System.out.println("YAHTZEE! Your total score is 50! Congratulations!");
} else
System.out.println("Your total score is: " + sum);
}
public static void main(String[] args) {
new YatzyGame().startGame();
}
}

public int[] rollDice(int[] dice) {
System.out.println("What dice do you want to reroll? Dices index are 0-4");
int diceToRoll = keyboard.nextInt();
dice[diceToRoll] = rnd.nextInt(DICEMAXVALUE) + 1;
}
Like this you can make a function:
public int[] reroll(int amountOfRerolls, int[] dices){
for(int i =0;i<dicesToReroll;i++){
this.rollDice(dices);
}
return dices;
}
This makes the programm a bit more modal since you can reuse your rollDice() method wherever you need it. Also you could expand it a bit by handing in the indexes that are allowed to be rerolled in case needed.
edit: style

Related

Vector in java always overwriting everything with the last value

I'm a beginner in java and I have the following exercise to solve:
Read a set of sports lottery bets to an unspecified number of players. After that, read the template, compare the result and display a message.
Bet Class: must contain the player's name and an integer vector with thirteen positions to store the bet: 1 – winner of team A, 2 – winner of team B, and 0 for draw. Create the necessary constructor methods and the toString method.
ReadBets Class: This class must have an attribute that is a vector of objects of the Bet class. In addition, this class must have a method to read the person's name and their sports lottery game. Create the necessary constructor methods and the toString method.
ReadTemplate Class: This class should read the correct answers from the sports lottery game and store the result in an integer vector. Create the necessary constructor methods and the toString method.
GenerateResult Class: this class must compare the players' bets with the result of the template and, if you have 6 correct answers, show the winner's name, his game and the message: “WINNER, CONGRATULATIONS”. Otherwise, show the player name and the message “Try again, this time you didn't win”.
Main Class: implement in this class the control and execution flow for this problem creating the necessary objects to solve this class.
There is a complicating factor for me which is that each object bet is composed of a string name with a vector with the bets.
I made a solution to the problem that already reads validating only the allowed values (0,1,2), reads the template and compares.
However, I noticed that the last name typed and the last bets are always being recorded in the vector. In all positions.
I'm hours assembling and disassembling the code and I can't find a way to solve it.
I read that it may have to do with the new but I didn't understand how to solve it because at each position of the vector of objects I need to give a new to create the object with the internal vector that will store that player's bets.
Below are my classes:
MAIN:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public void execute(){}
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
//ReadBet a = new ReadBet();
V_Bets a = new V_Bets();
System.out.println("Enter the total bets that will be placed");
a.totalBets(input.nextInt());
a.Data entry();
a.Data output();
ReadTemplate g = new ReadTemplate();
g.getTemplate();
GenerateResult gr = new GenerateResult();
gr.generateResult();
}
}
BETS:
import java.util.Arrays;
public class Bet {
private static String name;
public static int[] Bet vector =new int [6];
/*public String getName(){
return this.name;
}*/
public static String getName() {
return name;
}
public void setName(String name){
this.name=name;
}
#Override
public String toString() {
return "Bet [name=" + name + ",Betvector=" + Arrays.toString(Betvector) + "]";
}
public int getBet(int i) {
return this.vector Bets[i];
}
public void setBets(int[] bets) {
this.vector Bets = bets;
}
public int[] getCloneArray() {
returnVectorBets.clone();
}
}
V_BETS
import java.util.Scanner;
public class V_Bets {
Input Scanner = new Scanner (System.in);
private int size;
public static Total BetBets[] = new Bet[100];
//total Bets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
private Bet bets = new Bet();
int i=0;
int j=0;
public void dataentry() {
for(j=0;j<size;j++) { //for external - from J that controls the total bets that will be registered
totalBets[j] = new Bet(); //Creating a bet object for each registration - bet object contains name and bet vector of that bettor
System.out.println("Enter the name of the Player:");
totalStakes[j].setName(input.next()); //setting the player's name
// loop to set the guesses
System.out.println("Please enter guesses for each Sports Lottery game");
System.out.println("1 - Winner Team A, 2 - Winner Team B and 0 - Tie");
for ( i=0;i<bets.vetorApostas.length;i++) // receive the bet until it reaches 6
{
System.out.println("Game "+i +":");
totalStakes[j].vectorStakes[i] = input.nextInt(); // receive the user's bets
while (totalApostas[j].vectorApostas[i] < 0 ) // if the user enters a negative number it says to try again
{
System.err.println("Negative Number, try again:");
totalBets[j].vectorBets[i]= entry.nextInt();
}
if (totalApostas[j].vetorApostas[i] > 2) // if the number is greater than 2 it says to try again
{
while (totalBets[j].vectorBets[i] > 2 ) {
System.err.println("Please enter numbers between 0 and 2");
totalBets[j].vectorBets[i]= entry.nextInt();
}
}
}
}
}
/*public void dataoutput() {
//System.out.println("The player's name is:"+total Bets[i].getName());
System.out.println("Your Bet:");
for ( i=0;i < Bet.vectorBeats.length; i++){
System.out.print(+TotalStakes[i].vectorStakes[i].getStakes(i)+ " ");
}
}
public void dataoutput() {
System.out.println("Your Bet::");
for (j=0; j<totalBets[i].vectorBets.length; j++) {
System.err.print("Player "+Total Bets[j].getName()+" ");
for (i = 0; i < totalBets[i].vectorBets.length; i++) {
System.err.print(total Bets[j].vector Bets[i] + " ");
}
}
}*/
public void totalOfBets(int size) {
this.size = size;
}
public int getSize() {
return size;
}
}
TEMPLATE:
public class Template {
//private String name;
public static int[]vectorTemplate =new int [6];
public int getBet(int i) {
return this.vectorTemplate[i];
}
public void setBets(int[] bets) {
this.vectorTemplate = bets;
}
public int getTemplate(int i) {
return this.vectorTemplate[i];
}
public void setTemplate(int[] bets) {
this.vectorTemplate = bets;
}
}
READ TEMPLATE:
import java.util.Arrays;
import java.util.Scanner;
public class ReadTemplate {
private Template template = new Template();
Input Scanner = new Scanner (System.in);
int guesses;
int counter=0;
int j;
int x;
int i;
public void getTemplate() {
System.out.println(" ");
for ( j=0;j<6;j++) // Receive numbers until it reaches 6
{
System.out.println("Now Enter Game Template: "+j);
template.vectorTemplate[j]= entry.nextInt(); // Receive user numbers
while (template.vetorTemplate[j] < 0 ) // If you enter a negative number, ask the user to type again
{
System.err.println("Negative Number, try again:");
template.vectorTemplate[j]=input.nextInt();
}
if (template.vectorTemplate[j] > 2) // if the number is greater than 2 ask again
{
while (template.vectorTemplate[j] > 2 )
{
System.err.println("Please enter numbers between 0 and 2");
template.vectorTemplate[j]=input.nextInt();
}
}
}
//printing the template
System.out.println("Template:");
for (i = 0; i < template.vectorTemplate.length; i++) {
System.out.print(template.vectorTemplate[i] + " ");
}
}
}
GENERATE RESULTS:
public class GenerateResult extends ReadTemplate {
private Bet bets = new Bet();
private Template template = new Template();
//private v_bets v_bets = new v_bets();
private int size;
public void generateResult() {
//Checking if it's right
int x;
V_Bets a = new V_Bets();
for(j=0;j<2;j++) {
int i=0;
int counter=0;
for (x = 0; x < template.vectorTemplate.length; x++) {
if (a.totalStakes[j].vectorStakes[i] == template.vectorTemplate[x]) {
counter++;
}
i++;
}
System.out.println(" ");
System.out.println("Counter of Equals! "+counter);
if (counter <= 5){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("Try again, this time you won");
}
else if (counter == 6){
System.out.println("Player "+a.Total Bets[j].getName());
System.out.println("WINNER,CONGRATULATIONS!");
}
}
}
public void totalOfBets(int size) {
this.size = size;
}
}
I am immensely grateful to anyone who can help understand where I went wrong and how to evolve.

Finding the largest, second largest, second smallest, and smallest int from an array in java

I'm using a method to print the largest, second largest, smallest, and second smallest integers. This is what I have so far for the base:
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
This is the method being called so far:
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
The actual output is to formatted like
(largest,secondlargest),(smallest,secondsmallest)
I've never used an array before, and I'm not sure how to use loops with it to find the values. How do I begin this?
Here is the complete code for my program. You can disregard the second and third case, however, I still need help with the third. I need to display all prime numbers in order. Here is the requirement: Twin Prime Numbers: This should let the user specify a limit n (I used limit instead) (if n is 1000, then consider 1
to 1000), and lists the pairs of twin primes up to n. The sample run is (3,5),(5,7),(11,13),(17,19)
The complete code:
import java.util.Scanner;
public class PatternChecker{
// The scanner is accessible for every method included
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int limit;
System.out.println("List of Pattern Checker problems:\n1) Largest and Smallest Pairs\n2) Patterns of Triangles\n3) Twin Prime Pairs\n4) Quit");
System.out.print("Choice: ");
int choice = input.nextInt();
// The switch statement for the variable "choice" and each case
switch (choice) {
default:
System.out.println("\n*** INVALID OPTION");
break;
case 1:
System.out.print("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(pairs(limit));
break;
case 2:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(triangleOne(limit));
System.out.println(triangleTwo(limit));
System.out.println(triangleThree(limit));
System.out.println(triangleFour(limit));
break;
case 3:
System.out.println("\nEnter the Limit: ");
limit = input.nextInt();
System.out.println(primePairs(limit));
break;
case 4:
System.out.println("\n*** End");
break;
}
}
// Case 1 Method : Largest and Smallest Pairs
public static String pairs(int limit) {
System.out.println("*** Largest and Smallest Pairs");
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle One)
public static String triangleOne(int limit) {
System.out.println("*** Patterns of Triangles");
for (int x = 1; x <= limit; x++) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Two)
public static String triangleTwo(int limit) {
for (int x = limit; x > 0; x--) {
for (int y = 1; y <= x; y++) {
System.out.print(y + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Three)
public static String triangleThree(int limit) {
for (int row = 1; row <= limit; row++) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = row; num > 0; num--) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 2 Method: Patterns of Triangles (Triangle Four)
public static String triangleFour(int limit) {
for (int row = limit; row >= 0; row--) {
for (int space = (limit - row); space > 0; space--) {
System.out.print(" ");
}
for (int num = 1; num <= row; num++) {
System.out.print(num + " ");
}
System.out.println();
}
return "";
}
// Case 3 Method: Twin Prime Pairs
public static String primePairs(int limit) {
System.out.println("*** Twin Prime Numbers up to " + limit);
return "";
}
}
Ok based on the comment i have written a quick answer with arraylists. hope this helps.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class MaxMin {
private List<Integer> alist = new ArrayList<Integer>();
public static void main(String args[]) {
MaxMin maxmin = new MaxMin();
maxmin.init();
}
public void init() {
System.out.println("Welcome!!!");
readFromUser();
printUserList();
doSort();
display();
}
public void readFromUser() {
Scanner scanner = null;
try {
scanner = new Scanner(System.in);
System.out.print("Enter the total number of elements :");
Integer totalElements = scanner.nextInt();
for (int i=0;i<totalElements;i++) {
System.out.print("Enter the " + i +" number");
alist.add(scanner.nextInt());
}
}catch(Exception e) {
e.printStackTrace();
} finally {
scanner.close();
}
}
public void printUserList() {
System.out.println("user entered list is :");
System.out.println(alist);
}
public void doSort() {
Collections.sort(alist);
}
public void display() {
System.out.println("(" +alist.get(alist.size()-1)+ "," +alist.get(alist.size()-2)+ ")" + "(" +alist.get(0)+"," +alist.get(1) +")");
}
}
I hope this isn't a homework problem, but the idea is to use a loop with the array, and keep track of the largest and smallest numbers.
Start with assigning the smallest number variable to Integer.MAX_VALUE, so the first number you check will be assigned to the smallest number, because all integer values except 2^31 - 1 are smaller than Integer.MAX_VALUE, and you do that for biggest too, but with Integer.MIN_VALUE.
And then whenever you assign the biggest number again, you assign the secondBiggest variable to the "biggest" variable.
With that in mind, you just need to loop through the values of the array and check if they're larger than the biggest (in which you re-assign it) or smaller than the smallest(same thing as biggest).
int[] array = new int[]{5, 3, 4, 1, 2};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
^
Example of looping through an array
I created an example for you.
First of all it generates a list of prime numbers till the limit (in this case hardcoded 100). Next it asks for all prime pairs and prints them. The pairs are stored in an ArrayList so it is very easy to get the first and the last pair.
It's not realy hard to understand so I don't know what to explain. Take a look at the code and if you have any questions feel free to ask.
import java.util.ArrayList;
public class PatternChecker {
public ArrayList<Integer> primes = new ArrayList<>();
public static void main(String[] args) {
PatternChecker pc = new PatternChecker();
pc.detectPrimes(100);
ArrayList<int[]> numbers = pc.getPairs();
System.out.println("Print all pairs: ");
numbers.stream().forEach((intA)->System.out.println(intA[0]+" / "+intA[1]));
System.out.println("Print just the greatest and the smallest pair: ");
System.out.println("("+numbers.get(0)[0]+","+numbers.get(0)[1]+")");
System.out.println("("+numbers.get(numbers.size()-1)[0]+","+numbers.get(numbers.size()-1)[1]+")");
}
public void detectPrimes(int limit) {
for(int i=2;i<limit;i++)
if(isPrime(i))
primes.add(i);
}
protected boolean isPrime(int no) {
for(int i=0;i<primes.size();i++)
if(no % primes.get(i) == 0) return false;
return true;
}
public ArrayList<int[]> getPairs() {
ArrayList<int[]> result = new ArrayList<>();
int last = primes.get(0);
for(int i=1;i<primes.size();i++) {
if(primes.get(i)==last+2) {
int[] resH = new int[2];
resH[0] = last;
resH[1] = primes.get(i);
result.add(resH);
}
last = primes.get(i);
}
return result;
}
}

Java lottery program counter

I need my lottery program to count the number of times 0,1,2,3,4 or 5 numbers match after 10 runs, then display them. It is also supposed to keep track of the total jackpot by adding a certain amount to the jackpot depending on how many numbers won. My problem is that is is counting this correctly for each individual run but not for all ten runs total. here is what I have.
package assignment5;
import javax.swing.JOptionPane;
import java.util.Random;
public class assignment5
{
public static void main(String[] args)
{
for(int i = 0; i <10; i++)
{
lottery pic=new lottery();
pic.Get_player_numbers();
pic.Get_jackpot_number();
pic.Check_winner ();
pic.Write_data();
}}
}
class lottery
{
int[] picks= new int[5];
int[] cpick=new int[5];
int i;
int j,c;
int match=0;
void Get_player_numbers ()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="User Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
//void jackpot()
void Get_jackpot_number()
{
int ctemp,cdupflag=0;
for(j=0;j<=4;++j)
{
//YOU DO NOT NEED THE CNUMBERFLAG
//IF YOU GENERATED THE NUMBERS CORRECLTY, THE COMPUTER WILL NOT GENERATE ONE ABOVE 99 OR LESS THAN 1
cdupflag=0;
while(cdupflag==0)
{
ctemp = (int)Math.round(Math.random()*99)+1;
cdupflag=1;
for(c=0;c<=j;++c)
{
if(ctemp==cpick[c])
{
cdupflag=0;
}
}//inner for loop
if(cdupflag==1)
cpick[j]=ctemp;
}
}
String Jackpot="Computer Lottery numbers are: "+"\n";
//String computer = "";
for(j=0;j<=4;++j)
{
if(j==4)
Jackpot=Jackpot+cpick[j];
else
Jackpot=Jackpot+cpick[j]+"-";
}
JOptionPane.showMessageDialog(null,Jackpot,"Output:",JOptionPane.INFORMATION_MESSAGE);
}
void Check_winner ()
{
for(int i=0;i<=4;++i)
{
for(int j=0;j<=4;++j)
{
if(picks[i]==cpick[j])
{
match=match+1;
}
}
}
}
void Write_data ()
{
String print = "";
int jackpot = 2500000;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
if(match==0)
{
counter0++;
print=print+"There is no match"+"\n";
print=print+"please try again "+"\n";
jackpot=jackpot+25000;
}
else
if(match==1)
{
counter1++;
print=print+"There is one match"+"\n";
print=print+"You won 100 Dollars "+"\n";
jackpot=jackpot+100000;
}
else
if(match==2)
{
counter2++;
print=print+"There are two matches"+"\n";
print=print+"You won 1,000 Dollars"+"\n";
jackpot=jackpot+250000;
}
else
if(match==3)
{
counter3++;
print=print+"There are three matches"+"\n";
print=print+"You won 10,000 Dollars "+"\n";
jackpot=jackpot+500000;
}
else
if(match==4)
{
counter4++;
print=print+"There are four matches"+"\n";
print=print+"You won 100,000 Dollars "+"\n";
jackpot=jackpot+1000000;
}
else
if(match==5)
{
counter5++;
print=print+"There are five matches"+"\n";
print=print+"You won "+jackpot+" Dollars"+"\n";
jackpot=2500000;
}
JOptionPane.showMessageDialog(null,print,"Output:",JOptionPane.INFORMATION_MESSAGE);
System.out.println("zero matchers occured " +counter0+ " times");
System.out.println("The current jackpot is " +jackpot+ "");
}
}
//end of class lottery
Firstly, I'm not sure to understand everything as your code is a little messy and uncommented, you should try to clear it, it will be easier for you to understand and to find errors.
Concerning the problems that I am seeing:
If I correctly understand you want to keep the "Jackpot" over the 10 rounds. This is not happening because in your main function you are doing
for(int i = 0; i <10; i++)
{
lottery pic = new lottery();
....
}
Therefore you are creating a NEW lottery for each run and it replace the previous lotery by an empty one at each runs. Maybe this instead would work:
lottery pic = new lottery();
for(int i = 0; i <10; i++)
{
....
}
As well be careful to your variables "match" in your lotery class. At the end of "Write_data" I would advice you to do "match = 0;" otherwise matches will not restart at 0 for each run

How to take integers being printed by a method?

I am making a very simple blackjack game with one class and at least 2 methods. I want to take the random generated numbers that are being output (cards being dealt) and add them so I can make an if else statement to check if the total is over 21 causing the player to lose.
import java.util.*;
public class BlackJack {
private Scanner scan;
static Random generator = new Random();
public BlackJack(){
scan = new Scanner (System.in);
}
public static void main(String[] args) {
StarterCards();
Hit();
}
public static void Hit() {
System.out.println("Hit? (y or n)");
String yes = new String ("y");
Scanner input = new Scanner(System.in);
String yesorno = input.nextLine();
if(yesorno.equals(yes)) {
RandomCard();
Hit();
if()
} else {
System.out.println("Game Over");
}
}
public static void RandomCard() {
int card = generator.nextInt(10) + 1;
System.out.println("Card : "+ card);
int total2 = card;
}
public static void StarterCards() {
int card1 = generator.nextInt(10) + 1;
int card2 = generator.nextInt(10) + 1;
System.out.println("Card : "+ card1);
System.out.println("Card : "+ card2);
}
}
Re:
How to take integers being printed by a method?
The solution: don't have the method print anything. Instead have the method return the number, and let the calling code print it or do with the number whatever it wants to do.
i.e.,
public int myMethod() {
int someNumber = ....; // calculate it here
// System.out.println(someNumber); // don't print it here!
return someNumber
}

Do not why Array not storing numbers in java

hi im a beginner in java i am trying to write a program that records the value of three dice rolls in a game between two players. i have to utilise arrays. the problem is that when i print out to screen for some reason the value of each dice is 0 and it is not printing the randomly generated roll. the idea is when we print to screen it should say round 1 player 1: and display each number rolled on the three dice and then do a calculation and output the points dependant on weather they are three the same or all different etc.
This is what i have so far any help would be appreciated as i am a beginner and have been trying to figure this out for hours.
This is the first class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
import java.util.Scanner;
public class Dicegame {
static Scanner read = new Scanner (System.in);
public static void main(String[] args) {
int[] num = new int[3];
int numberOfRounds;
numberOfRounds = 0;
do {
//This will print out a request for the user
System.out.println("Please enter the number of rounds: \n");
//This will ensure the input value will remain above 0
numberOfRounds = read.nextInt(); } while (numberOfRounds < 1);
Dicegame2 Dicegame2Object = new Dicegame2(numberOfRounds);
//This is instantiating the scanner object
Dicegame1 Dicegame1Object = new Dicegame1(num[0], num[1], num[2]);
Dicegame1Object.order();
Dicegame2Object.diceValue();
for(int round=0;round<numberOfRounds;round++){
System.out.println("Round "+ (round+1)
+" Player1: "+ num[0]+num[1]+num[2]+
" Points: "); }
if(Dicegame1Object.threeAllTheSame()){
System.out.print(Dicegame2Object.sumOfDiceSame());;
}else{
if(Dicegame1Object.alInOrder()){
System.out.print(Dicegame2Object.sumOfDiceRun());
}else{
if(Dicegame1Object.twoSameOneDifferent()){
System.out.print(Dicegame2Object.sumOfDiceDifferent());
}else{
System.out.print(Dicegame2Object.sumOfDicePair());
}
}
}
}
}
This is the second class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
public class Dicegame1 {
//variables
private int Dice1;
private int Dice2;
private int Dice3;
int[] num = new int[3];
private final int numberOfThrows = 3;
//Constructor
public Dicegame1 (int D1, int D2, int D3)
//This is assigning local variables to class variables
{ num[0] = D1;
num[1] = D2;
num[2] = D3;
}
//This will calculate to see if the dice are all the same
//This is a boolean method which contains an if statement
public boolean threeAllTheSame(){
boolean trueOrNot;
if((num[0] == num[1])&&(num[1]==num[2])){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the dice are a pair
//This is a boolean method which contains an if statement
public boolean twoSameOneDifferent(){
boolean trueOrNot;
if (((num[0] == num[1])&&(num[1]!=num[2]))||
((num[1] == num[2])&&(num[2]!=num[0]))||
((num[0] == num[2])&&(num[0]!=num[1]))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the roll is a run
//This is a boolean method which contains an if statement
public boolean alInOrder(){
boolean trueOrNot;
if ((num[1] == (num[0]+1))&&
(num[2] == (num[1]+1))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will calculate to see if the dice are all different
//This is a boolean method which contains an if statement
public boolean allDifferent(){
boolean trueOrNot;
if ((num[0] != (num[1]))&&(num[1] != (num[2]))&&(num[2] != (num[0]))){
trueOrNot = true;
}else{
trueOrNot = false;
}
return trueOrNot;
}
//This will sort out the numbers of the array in order
public void order(){
Arrays.sort(num);
}
}
This is the third and final class
// Description: program to simulate two players each rolling three dice for a number of rounds
import java.util.Arrays;
import java.util.Random;
public class Dicegame2 {
//variables
private int numberOfRounds;
private int Dice1;
private int Dice2;
private int Dice3;
private Dicegame1[] match;
//constructor
public Dicegame2(int nOfRounds) {
numberOfRounds = nOfRounds;
match = new Dicegame1 [numberOfRounds];
}
public void diceValue() {
int[] num = new int[3];
for(int i=1;i<numberOfRounds;i++){
Dice1 = 1+(int)(6*Math.random());
Dice2 = 1+(int)(6*Math.random());
Dice3 = 1+(int)(6*Math.random());
match [i] = new Dicegame1(num[0], num[1], num[2]);
}
}
//This will calculate the sum of dice if all the same
public int sumOfDiceSame(){
int calc1;
int[] num = new int[3];
calc1 =((num[0]+num[1]+num[2])+60);
return calc1;
}
//This will calculate the sum of dice if its a pair
public int sumOfDicePair(){
int calc2;
int[] num = new int[3];
calc2 =((num[0]+num[1]+num[2])+20);
return calc2;
}
//This will calculate the sum of dice if its a run
public int sumOfDiceRun(){
int calc3;
int[] num = new int[3];
calc3 =((num[0]+num[1]+num[2])+40);
return calc3;
}
//This will calculate the sum of dice if all different
public int sumOfDiceDifferent(){
int calc4;
int[] num = new int[3];
calc4 =(num[0]+num[1]+num[2]);
return calc4;
}
}
As I was able to see into your code, you are printing the array of nums into your main, that are not set.
Second that array is not needed at all.
You have something like Dicegame2. From what I am seeing I would create additional method here that will return the array match.
Also I do not understand summing into this class. I would sum into Dicegame1 BUT I would remove new int[3] from there.
This are only guide lines. read variables scope, and for loops.

Categories