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!
Related
I'm very inexperienced with coding, and am trying to make a very basic text based rpg combat system using my limited knowledge and the internet. Ideally the program should allow you to choose a type of attack, take the stamina cost away from your max stamina, then tell you how much damage you've done. As of now I am just trying to get the "normal attack" to work, but whenever you run the code and choose an attack it continuously just repeats the instructions on how to attack. I have included both the code and a screenshot of what displays when running. I assume the problem lies with me misusing the while loop, as I don't know much about it.
import java.util.Scanner;
import java.util.Random;
public class RPGv1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("What is your name?");
String name = scan.nextLine();
System.out.println("\nWelcome to RPGv1 " + name + "!");
// Max Stats
int MaxHP = rand.nextInt(25) + 1;
int MaxMP = rand.nextInt(20) + 1;
int MaxStam = 15;
// Enemy 1 Stats
int En1HP = rand.nextInt(10) + 1;
int En1Stam = rand.nextInt(5) + 1;
// Combat
System.out.println("You are being approached by the evil Enemy 1!");
while (En1HP > 0) {
System.out.println("Type \"n\" to use your Normal Attack, \"h\" for your Heavy Attack, and \"f\" for your fireball.");
String combat = scan.nextLine();
if (combat == "n")
if (MaxStam >= 2) { //required stamina
int nDam = rand.nextInt(3) + 1; //damage
int nStam = rand.nextInt(5) + 1; //stamina use
MaxStam = MaxStam - nStam; //stamina being taken
System.out.println("You have dealt " + nDam + " damage, and have " + MaxStam + " Stamina remaining.");
} else {
System.out.println("You do not have enough stamina.");
}
}
}
}
enter image description here
You are never updating the value of En1HP variable, so it always remaings greater than 0, and thus loops goes for infinite.
To break the loop, you must need to update En1HP variable and set its value to less than zero on some condition.
Also as a code conventions, you should use camel-case naming convention for naming variable names.
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.
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 must ask the user to think of an integer between 1 and 1000. They do not type this number into the computer they just think of it.
- This program will make a random number.
- The user must indicate if the guess is too high, too low or correct (Hint the program can have the user type 1 for High 2 for low or 3 for correct)
- Your program will make another guess.
- The user must indicate if the guess is too high, too low or correct.
- This process goes on until the computer program guesses the users number. If you design your program correctly it should always guess the number in 10 tries or less.
Now I'm confused about its! I wrote this program but I don't know how to fix it.
public class NumberGenerating {
int generatedNumber;
public void generateRandomNumber(){
//generate a random number
this.generatedNumber=(int)(Math.random()*1000);
// System.out.println("Generated num is: "+this.generatedNumber);
}
}
and
import java.util.Scanner;
public class NumberGuessing {
byte count;
NumberGenerating newNumber=new NumberGenerating();
//boolean variable to determine if the loop should end
boolean shouldLoopEnd =true;
Scanner input=new Scanner(System.in);
byte userChoice;
int tempNumber, temp2Number;
int tempGenLowNumber=1000;
int tempGenHighNumber=1000;
int tempLowNumber;
// int tempLowNumberOld;
int tempHighNumber=1000;
// int tempHighNumberOld;
public void usingGenerateNumber(){
newNumber.generateRandomNumber();
}
public void isThatCorrect(){
this.temp2Number= newNumber.generatedNumber;
while(shouldLoopEnd){
System.out.println ("The computer guess number is: " + newNumber.generatedNumber);
System.out.println("You have three different choices:");
System.out.println("1. The guessed number was too high.\n"
+ "2. The guessed number was too low\n"
+ "3. The guessed number was correct!");
userChoice=input.nextByte();
if(userChoice==3){
System.out.println("Congratulation!\nGood Luck!");
shouldLoopEnd=false;
}
else if(userChoice==2){ //Call that the number was too low
// this.tempLowNumberOld=this.tempNumber;
while(true){
newNumber.generateRandomNumber();
this.tempNumber=newNumber.generatedNumber;
if(this.tempNumber>this.temp2Number && this.tempNumber<this.tempGenHighNumber //this.tempNumber>this.tempLowNumberOld &&
&& this.tempNumber<this.tempGenLowNumber){
this.tempGenLowNumber= this.tempNumber;
break;
}
}
}
else if(userChoice==1){ //Call that the number was too high
// this.tempHighNumberOld=this.tempNumber;
while(true){
newNumber.generateRandomNumber();
this.tempNumber=newNumber.generatedNumber;
if(this.tempNumber<this.temp2Number && this.tempNumber<this.tempGenLowNumber //this.tempNumber<this.tempHighNumberOld &&
&& this.tempNumber<this.tempGenHighNumber){
this.tempGenHighNumber= this.tempNumber;
break;
}
}
}
count++;
System.out.println("Loop number counter is: "+count);
}
}
}
and
import java.util.Scanner;
public class MainLoop {
public static void main(String[] args) {
NumberGuessing newNumber=new NumberGuessing();
newNumber.usingGenerateNumber();
newNumber.isThatCorrect();
}
}
You should actually never generate a random number (unless a homework criteria requires that of you).
Instead, you should guess 500. That number partitions the space from 1...1000 in half.
If the user's number is higher, guess 750 (mid-way between 500 and 1000). Continue to partition the range of possibly correct user numbers in half, until you reach the actual number.
If you do generate a new random number within the space of possibly correct numbers, you are not guaranteed to finish in 10 steps or less.
I am trying to create a die rolling program. The goal is to roll a die until the chosen value comes up a certain number of consecutive times (I used the programmer defined name "rollLength" for this). I am trying to display how many total rolls it took until the die value comes up consecutively. The problem is when I run the program it shows that the rollLength came up perfectly with no wasted rolls which I know is unrealistic. My question is if you can suggest what is wrong with my code. I am not sure if I am doing nested loops wrong.
Here is my code.
package lab03_schultz;
import java.util.Scanner;
import java.util.Random;
public class Lab03_Schultz {
public static void main(String[] args) {
// WRITE main's CODE HERE
Scanner keyboard = new Scanner(System.in);
Random randomNumber = new Random();
//declare variables
int value, nSides, rollLength, roll;
int turns=0, n=0, count=0, totalThrows=0;
//ask for input
System.out.println("Please enter the number of sides (2, 4, or 6): ");
nSides = keyboard.nextInt();
System.out.println("Enter the value sought. Must be in the range [1," + nSides + "]: ");
value = keyboard.nextInt();
System.out.println("Enter the length of the run.\n" + "Remember, the bigger it is the longer it will take to find it");
rollLength = keyboard.nextInt();
System.out.println("Enter number of times to run the experiment:");
turns = keyboard.nextInt();
while(n!=value) {
roll = randomNumber.nextInt(nSides)+1;
n++;
}
while(count!=rollLength){ //countinue till count = rollLength
if(n==value){
count++; //count how many times n == value, this is to represent consective rolls for the value
} else if (n!=value) { //if n is not the value counter starts over at zero
count=0;
}
if (n!=value) {//This will count how many times the die didn't come up with the value
totalThrows++;
}
}
System.out.println("totalThrows: " + totalThrows); //finding what totalThrows is
//adds rolls (without watched value) and (when it showed watch value) together
System.out.println("Your total throws are: " + (totalThrows+rollLength));
}
}
This can be done with just a single loop
int rollsInARow = 0; // store how many times we roll the value
int totalThrows = 0;
while(rollsInARow != rollLength) {
int roll = randomNumber.nextInt(nSides)+1;
if(roll == value) {
rollsInARow++; // Count consecutive rolls that are the wanted value
} else {
rollsInARow = 0; // Reset if we get a roll other than value
}
totalThrows++; // +1 after each roll
}
We loop until we have the wanted rollLength. Each loop generates a random number and compares it to value. If they are equal, increment the counter. If different, reset the counter. At the end of each loop, keep track of total rolls.
Also a tip. When using an if statement to check a true/false value (n == value), you can simply use an else statement to catch the n != value because there are only two cases.
if(n == value) {
count++;
} else { // The same functionality as else if(n != value)
count = 0;
}
Your first while loop will run until n is equal to the value. It will not move past that block of code until n is equal to value.