I have made a Dice game in Java using two files. The code runs perfectly, but it seems to have a logical error in it that I don't understand. In the game, it only outputs the same value as the previous roll. So if the die rolled a 6 and you rolled again, it would say you rolled a 6 again continuously. I'm trying to fix it currently but am having trouble. Any help would be greatly appreciated.
Here are the two programs:
import java.util.Scanner;
public class DiceGameTest {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
//declare instance variables
int choice = 0;
//int total;
//total = die1.getRoll() + die2.getRoll();
//create the 2 die
Dice die1 = new Dice();
//Dice die2 = new Dice();
//print out description of game
System.out.println("Welcome to Eric and John's Dice game!");
System.out.println("This dice game is very simple, here are the rules!");
System.out.println(" 1. Roll a die");
System.out.println(" 2. To win, you must get a 4 or higher");
System.out.println(" 3. Have Fun!\n");
//ask the user if they want to roll the dice or quit
System.out.println("Would you like to roll the die to start playing? Press 1 to roll or \"-1\" to quit");
//user's choice
choice = input.nextInt();
//if the user puts 1
if(choice == 1)
{
System.out.printf("You rolled a %d%n", die1.getRoll());
}
//play the game
do
{
die1.getRoll();
if(die1.getRoll() >= 4)
{
System.out.println("Hooray! You won by getting a: " + die1.getRoll());
}
else if(die1.getRoll() < 4)
{
System.out.println("Too Bad! Your roll was: " + die1.getRoll() + " and it was not greater than or equal to 4");
}
//ask the user if they want to roll the dice again or quit
System.out.println("Would you like to roll the die to start playing? Press 1 to roll or \"-1\" to quit");
//user's choice
choice = input.nextInt();
}while(choice != -1);
if(choice == -1)
{
System.out.println("You Quit the Game!");
}
}
}
And this
import java.util.Random; //class used to generate random number for dice roll
public class Dice {
private int numberSides;
private Random randomGenerator;
private int currentRoll;
//default constructor
Dice() {
randomGenerator = new Random(); //initialize random object
numberSides = 6; //default number of sides
currentRoll = randomGenerator.nextInt(numberSides)+1; //initialize roll (1-6)
}
public int getRoll() {
return currentRoll;
}
//"roll" a random integer between 1 and numberSides
public void roll() {
currentRoll = randomGenerator.nextInt(numberSides)+1; //reroll 1-6
}
}
Right now you just keep calling die1.getRoll at the beginning of your loop. That number is not changing unless you call roll.
Remove currentRoll from your constructor. You don't need to put it there. Then,
die1.getRoll()
Should be,
die1.roll()
In your do while loop like this
do
{
die1.roll();
if(die1.getRoll() >= 4)
{
System.out.println("Hooray! You won by getting a: " + die1.getRoll());
}
else if(die1.getRoll() < 4)
//rest of it
Alternatively, you could make a few modifications in your game and change your function.
public int getRoll()
{
roll();
return currentRoll;
}
Why does my Java dice game keep repeating its roll?
You keep getting the same random number because the only code which is responsible for generating a new random number lies in the constructor of your Dice class.
The constructor will only be invoked once upon instantiation. Calling getRoll() subsequently will just return you the same random number.
If you want to receive a new random number from getRoll(), you can do it as:
public int getRoll(){ //return a new dice roll every time
return (randomGenerator.nextInt(numberSides)+1);
}
If you like the Dice class to "remember" the current roll, you can have a method like:
public int roll(){ //return a new dice roll every time & save current
currentRoll = randomGenerator.nextInt(numberSides)+1;
return currentRoll;
}
How would I go about calling the roll()function a getRoll() function? Could you please specify?
You don't need both roll() and getRoll(), either one is enough to generate a new random number. You just have to make sure you are placing randomGenerator.nextInt(numberSides)+1 in your roll() or getRoll() method to make it work.
Related
I'm trying to make a small gambling game in Java where the user has two options.
A TextField where he can write in the amount of how much he wants to bet and a ComboBox where he can choose how many precent chance for him to win. The comboBox provides the options 10%, 20%, 30%, 40% and 50%.
My problem is that I don't know how to apply probability in java. I tried doing following:
public class GamblingGame {
private int rdmNumber;
private int wonValue;
public int winOrLose(int valueBetted, int precentToWin, Label label, int attempts){
precentToWin = precentToWin/10;
rdmNumber= ThreadLocalRandom.current().nextInt(precentToWin, 10 +1);
System.out.println("this is rdmnumber: " + rdmNumber);
System.out.println("this is precentowin number: " + precentToWin);
//if the number you rolled is equal to the precent you choose (ie if its 10, the number is 1, if its 20 the number is 2)
if(rdmNumber == precentToWin) {
wonValue = valueBetted/precentToWin *2;
System.out.println("You win!");
label.setStyle("-fx-text-fill: green");
label.setText("You won! You recieved: " + wonValue+" coins!");
}
else{
label.setStyle("-fx-text-fill: red");
label.setText("Gamble failed! You lost: " +valueBetted + " coins. ("+attempts+")");
wonValue = -valueBetted;
}
System.out.println(wonValue);
return wonValue;
}
}
The problem is that if, for instance, the user puts in 50% in the combobox he won't get a true 50% chance to win.
The number the dice would need to roll here is 5 in order to win, and the max value is 10. So the user would roll a number between 5-10 and when he hits 5, he'd win.
How do I make it so that the precentage of rolling the dice would be a true 50%? (and of course not ruin it so that if i put in a difference precentage as the parameter it wont ruin the method)
how about you try this function?
private static Random rd = new Random();
public static boolean winner(int prob)
{
int value = rd.nextInt(100);
System.out.println("GOT: "+value+" probability of winning:"+prob+"%");
if(prob>value)
return true;
else
return false;
}
in this case, the probability num should be bigger to the obtained random number.
so, if you run this.. it will work
public static void main(String[] args) {
//sure winner
System.out.println(winner(99));
//random winner
System.out.println(winner(50));
//not a chance
System.out.println(winner(10));
}
try Random
Random random = new Random();
int i = random.nextInt(100);
if(i<50){
//do something
}
Thank you so much to both people who replied! It made me realise all i had to do was change following.
rdmNumber= ThreadLocalRandom.current().nextInt(1, 10 +1);`
if(rdmNumber <= precentToWin)
so now, the numbers itll look through will always be 1-10, but the possiblities of getting it right won't be one number, but multiple numbers.
Thanks again!
In the interest of learning I decided to write up a coin flipping program. The coin is an enum and i have the program return that enum value. I also have the user input from a menu style but this was helped by following along in a Barnes and Nobles book I purchased a while back.
I think I have come to a weird cross road. i was wanting to basically return the enum value and such but remove the 'menu' aspect and replace it with the ability for the user to input how many flips they would like to do and also repeat the program if they want to (so instead of pressing 1 to flip each time they can input say 20000 and it would flip that many times i also think doing this would help with a fairness check as a true test of fairness would return almost even amounts of heads and tails if it were to flip that many times then pressing 0 for no flips would end the program) and i want to prompt the user and ask if they would like to repeat.
here is the program I have written:
import java.util.*;
public class CoinTossing
{
private enum Coin { HEADS, TAILS };
private static final Random randomNumbers = new Random();
private static final int HEAD = 1;
private static final int TAIL = 2;
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int choice;
int toss = 0;
int tosses = 0;
int frontflip = 0;
int backflip = 0;
Coin gameStatus;
System.out.println("Welcome to the Coin Toss Program.\n");
System.out.println("Choose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
while ( choice != 0 )
{
if ( choice == 1 )
{
int CoinTossed = Flip();
switch ( CoinTossed )
{
//added tosses to switch statement to make the counter work perfect.
case HEAD:
gameStatus = Coin.HEADS;
tosses++; // add amount of tosses
break;
default: // changed case TAIL to default. Easy and works.
gameStatus = Coin.TAILS;
tosses++; // add amount of tosses
break;
}
if ( gameStatus == Coin.HEADS )
{
frontflip++; //Add amount of heads
}
else // gameStatus == TAILS
backflip++; //Add amount of tails
}
// A try to make an real exit out of a program
if ( choice == 2 )
{
EndProgram( frontflip, backflip, tosses );
}
System.out.println("\nChoose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
}
}
//Toss the coin to determine 1 or 2.
public static int Flip()
{
int toss;
toss = 1 + randomNumbers.nextInt( 2 );
if ( toss == 1 )
{
System.out.println("You toss the coin and it lands on head!");
}
else
{
System.out.println("You toss the coin and it lands on tail!");
}
return toss;
}
public static void EndProgram( int frontflip, int backflip, int tosses )
{
System.out.printf("You have tossed %d times.\n", tosses);
System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
System.exit(0);
}
}
I think I need a do / while loop so that I can have the user answer the yes or no question of do you want to play again? and inside the loop I have a switch statement that also says if the user inputs 0 for the number of flips the program ends?
I thought I could add this snippet to get input:
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
number = input.nextInt();
I was thinking of creating a new variable and have the user set the number of tosses. Then compound the while loop check like so
while(choice != 0 && numTosses !=0)
and then decrease the count and I'll have to check that count and once it reaches 0 print results as far as how many heads and how many tails then prompt the user if they would like to play the game again but I am having trouble getting the right. honestly I don't even know why I'm trying to do this if but for the knowledge aspect so if you don't wanna help a broski out I understand. I feel like I am on the right track.
You can use 2 loops:
public class CoinFlip {
private enum Coin {
HEADS,
TAILS
};
public static void main(String[] arguments) {
new CoinFlip();
}
CoinFlip() {
Scanner input = new Scanner(System.in);
int heads = 0, tails = 0;
while (true) {
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
int number = input.nextInt();
if (number == 0)
break; // or System.exit
for (int i = 0; i < number; i++) {
Coin flipResult = flip();
switch (flipResult) {
case HEADS:
heads++;
break;
case TAILS:
tails++;
break;
}
}
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
private Coin flip() {
return Coin.values()[(int) (Math.random() * Coin.values().length)];
}
}
The while loop continues to ask the user to play again and again, if they put 0 your break it or exit it. In that loop, a for loop will iterate over the flips.
I'm taking a programming II class in which we've been working on programming classes. Now we've been assigned homework to write a driver class to incorporate these classes. The homework states
Using the die, dice, and player classes completed in class, write a
driver class to have three players taking turns rolling the dice.
First player to accumulate a total score of 35 or more is the winner."
For example, if player 1 rolls a 3, their score is 3. Then player 2
rolls. Then player 3. As each player rolls, their roll is added to
their previous score.
I've started writing it, but have been given the error that several items in my program cannot be resolved to a type. I also have absolutely no idea how to even begin creating a loop to do what is being asked. This is what I have so far:
import java.util.Scanner;
public class DiceRace {
public static void main(String[] args){
Player player1;
Player player2;
Player player3;
Dice dice;
Scanner keyboard;
keyboard=new Scanner(System.in);
dice=new Dice();
System.out.print("First player's name: ");
player1=keyboard.next();
System.out.print("Second player's name: ");
player2=keyboard.next();
System.out.print("Third player's name: ");
player3=keyboard.next();
}//Ending bracket of method main
}//Ending bracket of class DiceRace
You can create 3 methods, for each player, and a method that plays the game. In each player's method, it first calls the play method with a parameter containing the player name, and the play method prints it out so that the player knows who's turn it is. once the play method is done, it will call the next player method, then the player after that, and finally back to player 1.
It looks like you're a beginner. You should do some tutorials or stuff like that to know the basics :) Also, if you start getting familiar with an IDE (like Eclipse) then programming will be far more easy for you as IDEs can give you detailed descriptions of errors, even while writing the code.
In your above example you need to create two classes by yourself Dice and Player, as they are not in Java by default.
The method keyboard.next() reads an input from the console and returns it as object of the type String, not Player. Thus, you can not assign the variable player1 the result, a String.
What you probably want is a Player object having a member variable String name. Here's an example:
public final class Player {
private String mName;
public Player(final String name) {
mName = name;
}
public String getName() {
return mName;
}
}
Then you can do something like this in your main-method:
player1 = new Player(keyboard.next());
System.out.println("Name of player1 is: " + player1.getName());
Next you probably want a Dice to have a roll method:
public final class Dice() {
private Random mRandom;
public Dice() {
mRandom = new Random();
}
public int roll() {
// Returns a random number between 1 and 6 (inclusive)
return mRandom.nextInt(6) + 1;
}
}
Then, in your main you can do:
Dice dice = new Dice();
System.out.println("Let's roll the dice: " dice.roll());
Now to the games logic, let's keep it very simple, beginner friendly:
int player1Score = 0;
int player2Score = 0;
int player3Score = 0;
boolean finished = false;
boolean player1One = false;
boolean player2One = false;
boolean player3One = false;
// 0 is first player, 1 second and 2 third
int currentPlayer = 0;
while(!finished) {
int rollValue = dice.roll();
if (currentPlayer == 0) {
player1Score += rollValue;
} else if (currentPlayer == 1) {
player2Score += rollValue;
} else {
player3Score += rollValue;
}
player1One = player1Score >= 35;
player2One = player2Score >= 35;
player3One = player3Score >= 35;
finished = player1One || player2One || player3One;
// Increment and modulo 3 (numbers between 0 and 2)
currentPlayer = ((currentPlayer + 1) % 3);
}
Good luck :)
Im trying to create an enhanced game of pig, where the user can roll a user entered number of dice. if all the dice rolled were a one, then you lose your bank points, if on of them is one, you get no points and your bank is safe. otherwise, you get to bank the points you rolled. I'm trying to loop through a queue in order for each player to get their turn, but it just loops the same person in the queue asking for how many dice the player wants to roll, then gets a result and terminates. What am i doing wrong here?
Also here's the current console output:
import java.util.Scanner;
import java.util.stream.IntStream;
import javax.lang.model.element.Element;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class EnhancedGameOfPig {
static int count;
static int roll() {
return (int) (6.0 * Math.random()) + 1;
}
public static void play() {
Scanner sc = new Scanner(System.in);
Queue<Player> myQueue = new LinkedList<Player>();
System.out.println("How many players are there? (2-10 Max)");
int numOfPlayers = sc.nextInt();
sc.nextLine();
for (int i =0; i < numOfPlayers; i++) { // creates specified number of
// players and adds
// them to a queue
System.out.println("What is your name player " + (i+1) + "?");
String playerName = sc.nextLine();
Player player = new Player(playerName, 0);
myQueue.add(player);
}
System.out.println("How many points would you like to play to, to win?"); // sets
// the
// number
// of
// points
// required
// to
// win
// the
// game
int maxPoints = sc.nextInt();
sc.nextLine();
for (Player e : myQueue) {
System.out.println("How many dice would you like to roll " + myQueue.peek().getPlayerName() + " ?");
int numofDice = sc.nextInt();
sc.nextLine();
int[] diceArray = new int[numofDice]; // creates an array to hold
// values of each dice roll
for (int i = 0; i <= numofDice-1; i++) {
diceArray[i] = roll(); // rolls dice and adds dice roll values
// to array
if (diceArray[i] == 1) {
count++;
}
}
int first = diceArray[0]; // looks at first value of array
for (int element : diceArray) {
if (element == first && first == 1) { // checks to see if all
// rolls were 1's
System.out.println("All of the dice you rolled were ones! You loose all your banked points!");
myQueue.peek().setBankedPoints(0);
break;
}
}
if (count == 1) {
System.out.println("You rolled a one, so you don't get any points. Sorry!");
} else {
int sum = IntStream.of(diceArray).sum();
System.out.println(sum + " points have been added to your bank!");
myQueue.peek().bankedPoints += sum;
}
}
}
}
Your loop control iterates through each player in the queue.
for (Player e : myQueue) {
But throughout your loop body your refer only to first player in the queue, with myQueue.peek(). For example:
System.out.println("How many dice would you like to roll "
+ myQueue.peek().getPlayerName() + " ?");
The peek() method returns the first player in the queue, but you're trying to affect the player e. You can address this problem by using e instead of myQueue.peek(), throughout the loop body.
public static void main(String[] args)
{
int i = 0;
i = rollDice(11);
System.out.print(" \nThe number of rolls it took: " + i);
i = rollDice(5);
System.out.print(" \nThe number of rolls it took: " + i);
}
public static int rollDice(int desiredNum)
{
int dice1 = 0;
int dice2 = 0;
Random rand = new Random();
int sum = 0;
int count = 0;
do
{
dice1 = rand.nextInt(6) +1;
dice2 = rand.nextInt(6) +1;
sum = dice1 + dice2;
count++;
} while(sum != desiredNum);
return count;
}
}
Im wanting to make it where the user can enter their own desired sum of the numbers to be rolled .Also I'm wanting it to display the value of each rolled die as its rolled. It needs to allow the user to call the rollDice method as many times as they want to.
Heres my exmaple output
EX- Please enter the Desired number: 8
Roll 1: 4 6 Sum: 10
Roll 2: 3 5 Sum: 8
It took 2 rolls to get the Desired number.
The original code above WAS a lab i had to do a few weeks ago. But we have just started this. And im trying to get ahead of the class. And this community helps alot. Thanks in advance.
The simplest solution here is to read user input using a Scanner, until the user enters a nominated character which ends the program.
e.g.
public static void Main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter desired number:");
String in = scan.nextLine();
rollDice(Integer.parseInt(in));
// Implement console output formatting here
} while(!in.equalsIgnoreCase("q"))
}
Here, the user can roll the dice for their desired number as many times as they want. When they are finished, entering "q" or "Q" in the console will end the program.
Also see the Javadoc for Scanner.
Try separating it into a few different methods like this. It'll help you think about the problem in smaller parts.
public static void main(String[] args) {
String input = "";
while(true) {
//Request input
System.out.println("Please enter the Desired number:");
input = getInput();
//Try to turn the string into an integer
try {
int parsed = Integer.parseInt(input);
rollDice(parsed);
} catch (Exception e) {
break; //Stop asking when they enter something other than a number
}
}
}
private static String getInput() {
//Write the method for getting user input
}
private static void rollDice(int desiredNum) {
//Roll the dice and print the output until you get desiredNum
}
To repeat, add a statement where the user enters a character that determines whether or not the program repeats itself. For example:
char repeat = 'Y';
while (repeat == 'Y' || repeat == 'y') {
// Previous code goes here
System.out.println("Try again? {Y/N} --> ");
String temp = input.nextLine();
repeat = temp.charAt(0);
}