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.
Related
I've created many different types of method in my coding as my task requires to, so I faced some problems that I'm trying to incorporate loops that allow only 3 guesses from the user. After each round, the user has the option of whether to continue playing or to stop. How should I implement that? Also, any mistakes in my coding? Thank you in advanced!
import java.util.Random;
import java.util.Scanner;
public class GuessmyGame{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Random random = new Random();
int number = random.nextInt(100)+1;
printInstruction();
int guess = in.nextInt();
guessNum(number, guess);
numberOfTries(guessNum);
}
public static void printInstruction(){
System.out.println(" I am thinking of a number between 1 and 100.");
System.out.println(" Can you guess what it is? ");
System.out.println(" Type a number : ");
}
public static void guessNum(int number, int guess){
if (number == guess){
System.out.println("Congratulations! You got it right.");
}
else if(number > guess){
System.out.println("Your guess is too low.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
else{
System.out.println( "Your guess is too high.");
Scanner in = new Scanner(System.in);
guess = in.nextInt();
System.out.println("Your guess is: "+guess);
guessNum(number, guess);
}
}
public static void numberOfTries(int guessNum){
Random random = new Random();
int number = random.nextInt(100)+1;
for(int i = 0; i < 3; i++){
System.out.println("Out of guesses!");
System.out.println("The number was " + number);
}
}
}
Use a while loop and add a boolean condition.. let's call it canContinue. You'll also need to keep track of how many times the user has attempted to guess, let's say it's called attemptCount as well as the correctness of the user's latest guess (correctGuess).
When attemptCount is 3 or correctGuess is true, prompt the user if they want to continue. If their answer suggests they don't want to continue, set canContinue to false, which causes the exit the loop and complete. Otherwise, reset attemptCount (to 0 presumably to allow another 3 attempts). The code that follows highlights the requested logic. since it's clear the code provided in the question has many bugs.
var promptToRetry = false;
while (canContinue) {
if (correctGuess) {
// Let user know their guess was correct
promptToRetry = true;
}
if (attemptCount > 2) {
// Let user know they didn't get the right number
promptToRetry = true;
}
if (promptToRetry) {
boolean wantsToTryAgain = PromptUserToTryAgain(); //Code returning bool which prompts user if they want to try again (need to implement)
if (wantsToTryAgain) {
attemptCount = 0; //Resets attempt counter
correctGuess = false; //Resets the guess
promptToRetry = false;
} else {
canContinue = false; //Causes loop to exit
}
}
...
}
}
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.
I'm a noob programmer, but I've been stuck on this one bit of code. How do you recurse back to start? I've tried several different methods but they all either take a ridiculous amount of code or don't work properly. I've been trying to implement this "simple" piece of code in all of my programming assignments, but it hasn't been working out. Thanks!
p.s. I've already finished the assignment. I'm just trying to make it more "complete".
public class OddProduct {
public static void main(String[] args) {
//Inputs from user
System.out.println("Enter an odd number");
Scanner input_odd = new Scanner(System.in);
int odd = input_odd.nextInt();
int oddproduct = 1;
//Multiplies all odd integers
for (int counter = 1; counter <= odd; counter = counter + 2){
oddproduct = oddproduct * counter;
}//end of for- loop
System.out.printf("\nThe product of all the odd integers up to %d is %d\n",
odd, oddproduct);
/* MY NOTES FOR RECURSE
if (odd%2 == 1){ proceed normally}
else if (odd%2 != 1) { HOW TO LOOP BACK???}
else { println = "Application closed"}
*/
}//end of main method
}//end of OddProduct class
Based upon your Notes I think this is what you require
Scanner input_odd = new Scanner(System.in);
int odd = 0;
while (odd % 2 != 1) { // fails first time && if user enters even number
System.out.println("Enter an odd number");
odd = input_odd.nextInt();
}
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.
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);
}