Okay so I'm coding a roll the dice game on java - java

This is the code I have, but I want it to be able to roll the dice based on the number of trials the user inputs and then display the frequencies of each face.
This code isn't working as I would expect.
Also I would like to change the switch cases to if and else if statements, if anybody could help me out with that would be amazing, I've been working on this for a while now.
import java.util.Random;
import java.util.Scanner;
public class DieRoll {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random randomNumbers = new Random();
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
int trials;
int face;
System.out.println("Please enter the number of trials");
Scanner scan= new Scanner (System.in);
trials= scan.nextInt();
for(int rolls= 1; rolls==trials; rolls++);{
face= randomNumbers.nextInt(6) + 1;
// determine roll value 1-6 and increment appropriate counter
switch ( face )
{
case 1:
++one; // increment the 1s counter
break;
case 2:
++two; // increment the 2s counter
break;
case 3:
++three; // increment the 3s counter
break;
case 4:
++four; // increment the 4s counter
break;
case 5:
++five; // increment the 5s counter
break;
case 6:
++six; // increment the 6s counter
break; // optional at end of switch
}
}
System.out.println( "Face\tFrequency" ); // output headers
System.out.printf( "1\t%d\n2\t%d\n3\t%d\n4\t%d\n5\t%d\n6\t%d\n",
one, two, three, four,
five, six );
scan.close();
}
}

In your for loop:
Remove the semicolon (;) just after the for(int rolls= 1; rolls==trials; rolls++) line.
Change:
for(int rolls= 1; rolls==trials; rolls++)
to:
for(int rolls= 1; rolls<=trials; rolls++)
As far as changing switch to if-else-if, not sure why you would want to do this, but simply write it as:
if(face == 1){
one++;
}
else if(face ==2){
two++;
}
and so on..

Please have a look at this:
public class Main {
private static final Random RANDOM_NUMBER_GENERATOR = new Random();
public static void main(String[] args) {
int numberOfTrials;
int[] facesFrequencies = new int[6];
System.out.println("Please enter the number of trials");
Scanner scanner = new Scanner(System.in);
numberOfTrials = scanner.nextInt();
scanner.close();
for (int numberOfRolls = 1; numberOfRolls <= numberOfTrials; numberOfRolls++) {
int face = rollDice();
if (face == 1) {
facesFrequencies[0] += 1;
} else if (face == 2) {
facesFrequencies[1] += 1;
} else if (face == 3) {
facesFrequencies[2] += 1;
} else if (face == 4) {
facesFrequencies[3] += 1;
} else if (face == 5) {
facesFrequencies[4] += 1;
} else if (face == 6) {
facesFrequencies[5] += 1;
}
}
System.out.println("Face\tFrequency");
for (int i = 0; i < facesFrequencies.length; i++) {
System.out.printf("%d\t\t%d%n", i, facesFrequencies[i]);
}
}
private static int rollDice() {
return RANDOM_NUMBER_GENERATOR.nextInt(6) + 1;
}
}
I've put the results (int one to int six) into an array. facesFrequencies[0] will be the same as int one.
The ; after for (...) is syntactically incorrect.
Switch statement is replaced with if statement.

Related

Java mesurements

I wanted to program a little Program that generates an addition task with 4 random numbers with measurements, like 45mm+34dm+ and so on....
The second function is: when the user enters the right solution, in mm measurements in the console, the program should print out: "right". But on the second function lies the problem. Something doesn't work on the if statement I wrote for this function.
Here is the Code:
package Uebungen;
import java.util.Scanner;
import sun.applet.Main;
import java.util.Random;
public class AvuG {
// Programmstart
public static void main(String[] args) {
// Declarationen
Scanner scn= new Scanner(System.in);
Random rG = new Random();
int[] numbers = new int[4];
int[] measurments = new int[4];
//Fills Array with four Random numbers for future measurment generation
for (int i = 0; i < maßEinheiten.length; i++) {
measurments[i] = rG.nextInt(4);
}
// Fills Array with four random numbers
for (int i = 0; i < numbers.length; i++) {
numbers[i] = rG.nextInt(99);
}
// Prints out 4 numbers with measurments
for (int i = 0; i < numbers.length; i++) {
if (i == numbers.length - 1) {
System.out.print(data[i] + checkInput(measurments[i]));
} else {
System.out.print(data[i] + checkInput(measurments[i]) + " + ");
}
}
//Calculates Solution of the calculation in measure mm in the Background for future use.
for (int i = 0; i < measurments.length; i++) {
switch(measurments[i]) {
case 1:
result += numbers[i];
break;
case 2:
result += numbers[i] * 10;
break;
case 3:
result += numbers[i] * 1000;
break;
case 0:
result += numbers[i] * 100;
break;
}
}
// Solution of the calculation, so you dont have to calculate when you want to investigate if its working.
System.out.println("");
System.out.println(result + "mm");
// *** Here lies the Problem. If the Solution is right, it should print out: "Right".
int nutzereingabe2 = scn.nextInt();
String nutzerEingabe = scn.next();
String nutzerEingabe3 = nutzereingabe2 + nutzerEingabe;
if ( nutzerEingabe3 == (result+"mm")){
System.out.println(result + "mm");
}
}
// Measurment Generator
private static String checkInput(int i) {
String result = "";
switch (i) {
case 1:
result = "mm";
break;
case 2:
result = "cm";
break;
case 3:
result = "m";
break;
case 0:
result = "dm";
break;
default:
result = "Error";
}
return result;
}
}

Why does my simple poker program continue to draw the same cards?

I'm learning Java for my own and i have this problem:
I created a poker program, and every time, both the AI and I draw nothing but the Ace of Spades (5 each) every round. How can I fix this?
import java.io.IOException;
import java.util.Scanner;
public class poker {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int score1 = 0,score2 = 0;
for (int i=0; i<10; i++) {
int[][] previous_cards = new int[0][2];
int[][] hand1 = generate_hand(previous_cards);
int[][] sorted1 = sort_hand(hand1);
System.out.println("Round "+(i+1)+": ");
System.out.print(" Your hand: ");
print_hand(sorted1);
int identify_hand1 = identify_hand(sorted1);
System.out.print(" ");
print_identify_hand(identify_hand1);
System.out.println();
int[][] hand2 = generate_hand(hand1);
int[][] sorted2 = sort_hand(hand2);
System.out.print(" Computer hand: ");
print_hand(sorted2);
int identify_hand2 = identify_hand(sorted2);
System.out.print(" ");
print_identify_hand(identify_hand2);
System.out.println();
int compared = compare_hands(sorted1,sorted2);
if (compared==-1)
System.out.println(" You win this round!");
else if (compared==1)
System.out.println(" The computer wins this round!");
else System.out.println("Draw!");
score1 += (compared<0)?1:0;
score2 += (compared>0)?1:0;
System.out.println(" Score: You:"+score1+" - Computer:"+score2);
input.nextLine();
}
if (score1<score2)
System.out.println("The computer won with: "+score2+"-"+score1+".");
else if (score1==score2)
System.out.println("Draw: "+score1+"-"+score2+".");
else System.out.println("You won with: "+score1+"-"+score2+".");
}
public static int[][] generate_hand(int[][] previous_cards) {
int[][] hand = new int[5][2];
return hand;
}
public static int[] generate_card() {
int[] card = new int[2];
card[0] = (int) (Math.random()*13 + 2);
card[1] = (int) (Math.random()*4 + 1);
return card;
}
public static int compare_2_cards(int[] card1, int[] card2) {
return 0;
}
public static void print_hand(int[][] hand) {
System.out.print(card_to_String(hand[0])+", ");
System.out.print(card_to_String(hand[1])+", ");
System.out.print(card_to_String(hand[2])+", ");
System.out.print(card_to_String(hand[3])+", ");
System.out.print(card_to_String(hand[4]));
}
public static String card_to_String(int[] c) {
String card = "";
if (2<=c[0] && c[0]<=10)
card += c[0];
else if (c[0]==11) card += "Jack";
else if (c[0]==12) card += "Queen";
else if (c[0]==13) card += "king";
else card += "Ace";
card += " of ";
if (c[1]==1) card += "hearts";
else if (c[1]==2) card += "diamonds";
else if (c[1]==2) card += "clubs";
else card += "spades";
return card;
}
public static int[][] sort_hand(int[][] hand) {
int[][] sorted = new int[5][2];
return sorted;
}
public static void print_identify_hand(int identify_hand) {
if (identify_hand==1)
System.out.print("(straight flush)");
else if (identify_hand==2)
System.out.print("(four of a kind)");
else if (identify_hand==3)
System.out.print("(full house)");
else if (identify_hand==3)
System.out.print("(four of a kind)");
else if (identify_hand==4)
System.out.print("(flush)");
else if (identify_hand==5)
System.out.print("(straight)");
else if (identify_hand==6)
System.out.print("(three of a kind)");
else if (identify_hand==7)
System.out.print("(two pairs)");
else if (identify_hand==8)
System.out.print("(one pair)");
else
System.out.print("(nothing - high hand comparison)");
}
public static int compare_hands(int[][] hand1,int[][] hand2) {
// IMPLEMENT: compare 2 cards
return 1;
}
public static int identify_hand(int[][] hand) {
if (hand[0][1]==hand[1][1] && hand[1][1]==hand[2][1] && hand[2][1]==hand[3][1] && hand[3][1]==hand[4][1] && // compare that they have the same suit
hand[0][0]+1==hand[1][0] && hand[1][0]+1==hand[2][0] && hand[2][0]+1==hand[3][0] && hand[3][0]+1==hand[4][0]) // compare card numbers
return 1;
if (hand[0][0]==hand[1][0] && hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0]) // compare card numbers
return 2;
if (hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0] && hand[3][0]==hand[4][0]) // compare card numbers
return 2;
return 9;
}
}
Your int[][] hand objects are empty.
The generate_hand method returns an empty array, sort_hand returns another empty array, the other methods don't alter the array at all.
You end up passing empty (for int arrays, that means that each index contains 0) arrays to card_to_String, which then displays the result for c[0] == 0 and c[1] == 0, you got it...this is Ace of spades.

Poker dice game, and I don't know why my methods have errors on them

public static void main(String[] args) {
Scanner inScanner = new Scanner(System.in);
int[] dice = new int[5];
resetDice(dice);
System.out.print("Your current dice: + dice");
rollDice(dice);
System.out.print(dice);
System.out.println();
promptForReroll(dice, inScanner);
System.out.println("Rerolling...");
rollDice(dice);
System.out.println("Your final dice: + dice");
System.out.println(getResult(dice)+"!");
}
private static void resetDice(int[] dice) {
int length = 5;
for(int i = 0; i < length; i++){
dice[i] = 0;
}
}
private static void rollDice(int[] dice) {
int i = 0;
int length = 5;
while(i < length) {
if(dice[i] == 0) {
int roll = (int)(Math.random()*6)+1;
dice[i] = roll;
i++;
}
}
}
private static String diceToString(int[] dice) {
String diceToString =("Your current dice: " +dice[0]+", " +dice[1]+ ", " +dice[2]+ ", " +dice[3]+ ", " +dice[4]);
return diceToString;
}
private static void promptForReroll(int[] dice, Scanner inScanner) {
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
int selection = inScanner.nextInt();
while(selection != -1){
if(selection > 4 || selection < -1){
System.out.println("Erorr: Index must be between 0 and 4 (-1 to quit)!");
}
else{
dice[selection] = 0;
}
System.out.println("Your current dice: " + dice);
System.out.print("Select a die to re-roll (-1 to keep remaining dice): ");
selection = inScanner.nextInt();
}
System.out.println("Keeping remaining die...");
}
private static boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
}
private static String getResult(int[] dice) {
getCounts(dice);
}
private static int[] getCounts(int[] dice) {
int[] count = new int[6];
int i = 0;
int j = 0;
while(i<5){
while(j<5){
if(dice[i] == (j+1)){
count[j]++;
i++;
}
else{
i++;
}
j++;
}
}
return count;
}
I have written out the coding, and I think for the most part it may be right, but I can't run it because it has errors on my promptForPlayAgain method, and my getResult method. I don't know why there are errors on them.
You aren't returning anything if the user's input isn't "Y" or "N". You need to add an else case:
private static Boolean promptForPlayAgain(Scanner inScanner) {
System.out.println("Would you like to play again?(Y or N)");
String play = inScanner.nextLine();
if(play=="Y"){
return true;
}
else if(play=="N"){
return false;
}
else
{
//Do something here to handle bad input.
}
}
Ideally though, you should be doing some kind of formatting and preverification of the input, like forcing the input to upper case before comparing.
And on getResult, you aren't returning anything. Add a return before the body of the function. That won't fix it though, since the return type of getValue doesn't match getResult. You're trying to return a int array as a string.
In the future, please include the actual error messages they you receive.

Java - How to contain a switch statement menu in a while loop

I have a main menu class which gets a choice from the user and then uses that choice to select other classes from a switch statement pertaining to the menu options. My code is:
public static void main(String[] args) {
int dieOne = 0;
int dieTwo = 0;
int choice = 0;
DiceMaker dice = new DiceMaker(); // class that creates the dice
RollDice roll = new RollDice(); // class that imitates roll
DiceMenu menu = new DiceMenu();
DiceRoller series = new DiceRoller();
System.out.println("Welcome to the Dice Roll Stats Calculator!\n");
while (choice != 4) {
menu.DiceMenu();
choice = menu.getUserChoice();
switch (choice) {
case 1:
dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dice.DieOne() + dice.DieTwo());
return;
case 2:
roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
return;
case 3:
series.diceRoller();
series.displayResults();
return;
case 4:
break;
}// switch (choice)
} // while (choice != 4)
}
Case for is the 'Exit' option, so I put the switch statement in a while loop with the boolean condition being not equal to 4 so that when the choice was set to 4 the loop would stop. The proper case executes but the problem I'm having is that the loop, and consequently the program stop after each case that I try, even if the choice was not 4. I tried using break statements after case 1, 2 and 3 as well, and when I did that, it would just repeat the case in an infinite loop. I tried to figure this out on my own cut could never find anything that resembled what I was seeing enough for me to figure out what the problem was. I'm guessing this probably isn't the best way to make a menu in the future. Thank in advance.
The rest of my code is as follows. Please note, DiceRoller class is still under construction, but DiceMaker and RollDice classes seem to be working.
DiceMenu class:
public class DiceMenu
{
public static final int CHOICE_UNKNOWN = 0;
public static final int CHOICE_MAKE_DICE = 1;
public static final int CHOICE_ROLL_ONCE = 2;
public static final int CHOICE_SERIES_ROLL = 3;
public static final int CHOICE_QUIT = 4;
private int choice = 0;
Scanner scan = new Scanner(System.in);
public int DiceMenu()
{
while ( this.choice < 1 || this.choice > 4 ) // while loop keeps choices in range
{
System.out.println(" MAIN MENU\n");
System.out.println("1. Create Your Dice");
System.out.println("2. Roll Your Dice");
System.out.println("3. Perform A Series Of Rolls And Show Stats");
System.out.println("4. Exit\n");
try // avoid invalid input
{
System.out.print("Please choose an option: ");
this.choice = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if ( this.choice < 1 || this.choice > 4 ) // if input is out of range
// notify user before continuing
{
System.out.println("Choice must reflect menu options. (1-4)"
+ " Please try again.\n");
this.choice = 0;
}
}//while ( this.choice < 1 || this.choice > 4 )
return 0;
}
public int getUserChoice()
{
return this.choice;
}
}
RollDice class:
public class RollDice
{
private int roll;
private int rollOne;
private int rollTwo;
private int rollTotal;
public int rollDice (int dieOne, int dieTwo)
{
this.rollOne = 1 + (int)(Math.random() * dieOne);
this.rollTwo = 1 + (int)(Math.random() * dieTwo);
this.rollTotal = this.rollOne + this.rollTwo;
return 0;
}
public void displayRoll()
{
System.out.println("You roll a " + rollOne + " and a "
+ rollTwo + " for a total of " +
rollTotal + "!"); //display separate and total
//roll amounts
if ( rollTotal == 2 ) // if/else tests for special rolls
{
System.out.println("Snake Eyes!");
}
else if ( rollTotal == 7 )
{
System.out.println("Craps!");
}
else if ( rollOne == 6 && rollTwo == 6 )
{
System.out.println("Boxcars!");
}
}
}// public class DiceRoller
DiceMaker class:
public class DiceMaker
{
private int sides = 0;
private int dieOne;
private int dieTwo;
public int diceMaker()
{
while ( sides < 4 || sides > 20 ) // while loop keeps sides within range
{
Scanner scan = new Scanner(System.in);
try // avoid invalid input
{
System.out.print("Please enter the number of sides each die "
+ "should have (must be between 4 and 20): ");
this.sides = scan.nextInt(); // get number of sides from user
}
catch (InputMismatchException e)
{
//if input is invalid, returns to beginning of loop
System.out.println("Invalid Input. Please try again.\n");
scan.next();
continue;
}
if (sides < 4 || sides > 20) // if input is out of range
// notify user before continuing
{
System.out.println("Die must have between 4 and 20 sides."
+ " Please try again.\n");
}
}//while ( sides < 4 || sides > 20 )
this.dieOne = sides;
this.dieTwo = sides;
return 0;
}
public int DieOne()
{
return this.dieOne;
}
public int DieTwo()
{
return this.dieTwo;
}
}// public class DiceMaker
Remove the return(s) from cases 1,2 and 3. If you return from main the program terminates. You want to loop so don't do that. However, as pointed out by #ajb in the comments below, you don't want the case(s) to fall through. So you need break(s).
case 1: dice.diceMaker();
dieOne = dice.DieOne();
dieTwo = dice.DieTwo();
System.out.println(dieOne + dieTwo);
// return;
break; // <-- applies to innermost block (switch).
case 2: roll.rollDice(dieOne, dieTwo);
roll.displayRoll();
// return;
break; // <-- applies to innermost block (switch).
case 3: series.diceRoller();
series.displayResults();
// return;
break; // <-- applies to innermost block (switch).
Also, you could use continue (here, which would apply to the innermost loop). Finally, remember that case 4 terminates the loop (because choice is 4) and you don't need case 4 for that reason.

Poker EV calculator: Computing Hand Value?

I am attempting to write a program that helps a user make the correct EV play for each hand. However at the minute I am using card value (i.e. total of two cards) to base my decisions. For example 9=9, 10=10, j=11, q=12.... I would like the use to be able to enter in their actualy hands e.g. Adks (ace of diamonds, king of spades). This would be more accurate as it would take into account the suited value of the hand etc. Can anyone give me advice on the best way to incorporate this? Many thanks in advance! My cuurent code is below!
package uk.ac.qub.lectures;
//importing resources (scanner)
import java.util.Scanner;
public class PokeGame {
public static final int MIN_POSITION = 1;
public static final int MAX_POSITION = 8;
public static void main(String[] args) {
// declaring user position
int userPosition = 0;
// setting up scanner
Scanner scanner = new Scanner(System.in);
// integer referring to use again or not
int useAgain = 0;
// boolean getting valid input for repeat
boolean repeat = false;
// declaring number value of each card
int cards;
do {
// getting user position
do {
System.out.printf("Please enter position between %d and %d\n",MIN_POSITION, MAX_POSITION);
userPosition = scanner.nextInt();
} while ((userPosition < MIN_POSITION) || (userPosition > MAX_POSITION));
// getting hand hand strength
System.out.println("Enter card value");
cards = scanner.nextInt();
switch (userPosition) {
case 1:
case 2:
if (cards > 10) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 3:
case 4:
case 5:
if (cards > 13) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
case 6:
case 7:
case 8:
if (cards > 17) {
System.out.println("SHOVE");
} else
System.out.println("FOLD");
break;
default:
System.out.println("ENTER VALID POSITION");
}
do {
System.out.println("Do you advice on another Hand?");
System.out.println("Enter 1 for Yes, Enter 0 for No");
useAgain = scanner.nextInt();
if ((useAgain == 1) || (useAgain == 0)) {
repeat = false;
} else {
System.out.println("Invalid Input, please enter 1 or 0");
repeat = true;
}
} while (repeat);
} while (useAgain != 0);
// clean up resources
scanner.close();
}// method end
}// class end
If you take the card input like this; "AA", "9T" or "9Ts", you can then compute a hand value based on suitedness and gaps like such using you input cards:
import java.util.Arrays;
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String[] hand = (scanner.nextLine() + 'u').toUpperCase().split("");
String values = " 23456789TJQKA";
int[] cards = new int[] {values.indexOf(hand[1]), values.indexOf(hand[2])};
Arrays.sort(cards);
int gap = cards[1] - cards[0] - 1;
boolean pair = gap == -1;
boolean suited = hand[3].equals("S");
char[] cards = new char[] {(char)values.charAt(cards[0]), (char)values.charAt(cards[1])};
int handValue = 0;
// adjust value based on pairs, suitedness or connectedness
if (pair) // hand is a pair
handValue += 10; //or whatever you want
else if (suited) // hand is suited
handValue += 3; //or whatever you want
if (gap == 0) // hand is no gap
handValue += 5; //or whatever you want.
if (gap == 1) // hand is one gap
handValue += 3; //or whatever you want.
if (cards[1] == 'A' && cards[0] == 'K' && suited) // AK suited
System.out.println("AK Suited!");
else if (cards[1] == 'A' && suited) // Ax suited
System.out.println("Ax Suited!");

Categories

Resources