Coin Toss JavaScript with user input - java

Write a program to simulate a coin toss. First, ask the user to "call" or predict the toss. Next, let the user know you are tossing the coin. Then report whether the user was correct.
Example:
Please call the coin toss (h or t): h
Tossing...
The coin came up heads. You win!
This is about what I am supposed to do. This is the code I have so far:
package inClassCh4Sec8to9;
import java.util.Random;
import java.util.Scanner;
public class ClassCh4Sec8to9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter you guess (1 for heads, 0 for tails, 2 to quit):");
int call = input.nextInt();
int heads = 1;
int quit = 2;
int tails = 0;
if (call == quit) {
break;
} else if (call == heads) {
} else if (call == tails) {
} else {
System.out.println("invalid");
continue;
}
Random random = new Random();
int coinflip = random.nextInt(2);
if(call == coinflip){
System.out.println("Correct!");
}else{
System.out.println("Sorry, incorrect.");
}
}
}
}
My problems:
I can get a random number no problem but it allows the h and t to be used as 1 and 0.
I want h or heads to equal 1 as an input.

Instead of Random.nextInt(), I would prefer nextBoolean(). Don't redeclare your Random in a loop. If the input starts with an h set a guess to true; otherwise, make sure it is valid (and set it false). Then flip the coin, and compare the result. Something like,
Scanner input = new Scanner(System.in);
Random random = new Random();
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine().toLowerCase();
boolean guess = call.startsWith("h"), coin = random.nextBoolean();
if (call.startsWith("q")) {
break;
} else if (!guess && !call.startsWith("t")) {
System.out.println("invalid");
continue;
}
if ((guess && coin) || (!guess && !coin)) {
System.out.printf("The coin came up %s. You win!%n", coin ? "heads" : "tails");
} else {
System.out.printf("The coin came up %s. You lose!%n", coin ? "heads" : "tails");
}
}

import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Please call the coin toss (h or t): ");
String call = input.nextLine();
String heads = "h";
String tails = "t";
if(call==null || call.length() > 1){
break;
}
System.out.println("Tossing...");
int random=(int)(Math.random()*2);
if(random<1){ //assume that, if random variable is smaller than 1 then it is head. If bigger than 1 and smaller than 2, then tails.
if(heads.equals(call)){
System.out.println("The coin came up heads. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}else{
if(tails.equals(call)){
System.out.println("The coin came up tails. You win!");
}
else{
System.out.println("Sorry, incorrect.");
}
}
}
}
}

Related

Keeping a tally of how many times a number appears using a random number generator. Java

In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
if (sideup == 1) {
return Coin.Head;
} else {
return Coin.Tail;
}
}
}
You can for example add two fields in your CoinToss class. Like int heads and int tails. Initialize them with 0 in the startGame() method. Then, in the tosscoin() method:
if (sideup == 1) {
heads++;
return Coin.Head;
} else {
tails++;
return Coin.Tail;
}
You can access these fields in the startGame() method and do whatever you want with them.
You could as well define these two variables directly in the startGame() method and increment them based on the type of Coin which you get from the tosscoin() method.
Below code should work. everytime it tosses, it stores the current value in a variable and compares it next time with the toss value.
import java.util.Random;
import java.util.Scanner;
public class CoinToss {
private static int headCounter;
private static int tailCounter;
private static int previousToss;
private enum Coin {
Head, Tail
}
public static void main(String[] args) {
CoinToss game = new CoinToss();
game.startGame();
}
private void startGame() {
headCounter = 0;
tailCounter = 0;
previousToss = 0;
Scanner scanner = new Scanner(System.in);
Coin guess;
while (true) {
System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
String choice = scanner.nextLine();
if (choice.equalsIgnoreCase("3")) {
break;
} else if (choice.equalsIgnoreCase("1")) {
guess = Coin.Head;
} else if (choice.equalsIgnoreCase("2")) {
guess = Coin.Tail;
} else {
System.out.println("Please select either heads tails or quit.");
continue;
}
Coin toss = tosscoin();
if (guess == toss) {
System.out.println("You guessed correctly!");
} else {
System.out.println("You guessed incorrectly");
}
}
scanner.close();
}
private Coin tosscoin() {
Random r = new Random();
int sideup = r.nextInt(2);
Coin currentGuess;
if (sideup == 1) {
headCounter++;
currentGuess = Coin.Head;
} else {
tailCounter++;
currentGuess = Coin.Tail;
}
checkIfFlipped(sideup);
return currentGuess;
}
static void checkIfFlipped(int currentToss) {
if (currentToss != previousToss) {
if (currentToss == 0) {
System.out.println("Coin fliped from head to tail");
} else {
System.out.println("Coin fliped from tail to head");
}
}
previousToss = currentToss;
}
}

Why is this While Loop not executing properly

The goal of the game is to use a while loop. In this loop, it will determine who wins the game based on the number entered. The numbers are from 1 to 20. Challenge is the variable set at 10. If <= Challenge, playerOne loses one point. If > challenge, the monster loses a point. Whoever loses 3 points first loses the game. I do not need to have random number generation, I just need inputs via the scanner function.
I thought variables were necessary for the scanner, which is why I added the Dice variables. They are not used and I am confused if I need them or not to make the scanner work so that the user can make inputs.
I am also confused on how to subtrack from the player and monster when they get hit. Which is why I set the variables under each block for the amount of points they have. This is wrong but I am stuck as to how to properly display this.
I was able to get some messages to display, but any number would give me the same result which was -1 for player one.
Essentially I am stuck on how to write this in code from here. Any help is greatly appreciated.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(20);
}
public static void task3(int challenge) {
challenge = 10;
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
System.out.println("Enter your dice roll");
int diceRollOne = sc.nextInt();
while (player <= challenge) {
System.out.println("Monster misses");
System.out.println("Enter your dice roll");
int diceRollTwo = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 2;
System.out.println("Enter your dice roll");
int diceRollThree = sc.nextInt();
} else if (player > challenge) {
System.out.println("-1 for monster");
monster = 2;
System.out.println("Enter your dice roll");
int diceRollFour = sc.nextInt();
continue;
if (player <= challenge) {
System.out.println("-1 for player");
player = 1;
System.out.println("Enter your dice roll");
int diceRollFive = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 1;
System.out.println("Enter your dice roll");
int diceRollSix = sc.nextInt();
continue;
} else if (player <= challenge) {
System.out.println("-1 for player");
player = 0;
System.out.println("Monster Wins");
int diceRollSeven = sc.nextInt();
continue;
if (player > challenge) {
System.out.println("-1 for monster");
monster = 0;
System.out.println("Player wins!");
int diceRollEight = sc.nextInt();
}
}
}
}
}
}
}
When you are writing a while-loop, you must first think about the condition of when will the loop terminate / when will the loop continue. In your case, you want the loop to end when either player or monster become 0. Therefore the condition for the while-loop to continue running is the opposite, i.e. both of them > 0.
Then think about what do you want to do in each iteration. In your case, the repetitive tasks are
Read an integer from user input
compare the integer with challenge
subtract 1 point from the corresponding variable
Finally, after the loop ended, you can use the value of player and monster to determine the result and print it out.
import java.util.Scanner;
public class Task3 {
public static void main(String args[]) {
task3(10);
}
public static void task3(int challenge)
{
int player = 3;
int monster = 3;
int dice = 0;
Scanner sc = new Scanner(System.in);
while(player > 0 && monster > 0)
{
System.out.println("Enter your dice roll");
dice = sc.nextInt();
if(dice > challenge)
{
monster--;
}
else
{
player--;
}
}
if(player > monster)
{
System.out.println("Player wins!");
}
else
{
System.out.println("Monster wins!");
}
}
}
P.S. Try to understand the code instead of just copy and paste to your homework :)
You dont need to have a seperate variable to get each input from the scanner.
You can get the input each time in the while loop and compare the value to challenge.
we will exit the loop only when player or monster becomes zero.
once outside the loop, you can check who won and print the result accordingly.
import java.util.Scanner;
public class Task3 {
public static void main(String[] args) {
task3(10);
}
public static void task3(int challenge) {
int player = 3;
int monster = 3;
Scanner sc = new Scanner(System.in);
int diceRoll;
while (player == 0 || monster == 0) {
System.out.println("Enter your dice roll");
diceRoll = sc.nextInt();
if(player < challenge)
player--;
else
monster--;
}
if(player < monster)
System.out.println("Player wins!");
else
System.out.println("Monster Wins");
}
}
if you want only numbers between 1 and 20 as the input, you should also add an if condition which checks this after getting the input

Multiplayer Random Number Guessing Game: How to create random number for each player? [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I am creating a random number generator multiplayer game (LAN).
I need help on how to create a code to make each player receive their own random number, and whenever one player guesses a code, the next turn would be a new player. Similar to where the output would show the following,
Fred, Please Guess the random number (integers only!!): 5
TOO LOW
Tom, Please Guess the random number (integers only!!): 95
TOO HIGH
John, Please Guess the random number (integers only!!): 50
TOO LOW
Then when a player guesses correctly, their turn is skipped and the game will end when all players have guessed their numbers, showing the number to guesses each person had, as well as the numbers they guessed previously.
This is what I have so far:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Integer> guessedNumbers = new ArrayList();
int x = 0;
int players = 0;
System.out.println("how many players are there?:");
players = checkint(players);
int arraySize = guessedNumbers.size();
int[] numPlayers = new int [players];
boolean play = true;
boolean validGuess = true;
String [] pNames = new String[players];
for (int i = 0; i<players; i++) {
System.out.println("New player, what is your name?:");
pNames[i] = keyboard.nextLine();
}
while(play) {
int randNum = myRand.nextInt(100) + 1;
int numOfGuesses = 0;
do {
System.out.println("Enter what you think the number is between 0 and 100!:");
x= checkint(x);
guessedNumbers.add(x);
if (x < 0) {
System.out.println("we don't accept negative numbers");
if (x > 100) {
System.out.println("that number is above the random number generator range");
}
}
numOfGuesses++;
if (x == randNum) {
System.out.println("that's correct!");
System.out.println("It took you " + numOfGuesses + " tries!");
System.out.print("these are all the numbers you guessed:");
for(int count=0; count<guessedNumbers.size(); count++){
System.out.print(guessedNumbers.get(count) + ",");}
System.out.println("");
boolean playError = true;
//if ("Yes".equals(answer)) {
do {
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0) {
play = true;
playError = false;
} else if (answer.compareToIgnoreCase("no") == 0) {
play =false;
playError = false;
System.out.println("Thank you for playing");
} else {
//you messed up
System.out.println("You answer was invalid");
playError = true;
}
} while (playError == true);
}
else if
(x>randNum)
System.out.println("Lower than that!");
else if
(x<randNum)
System.out.println("Higher than that!");
} while (x != randNum);
}}
}
static int checkint(int a) {
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
String enteredString = "";
do {
try {
enteredString = myScanner.next(); //Read into a string
enteredNumber = Integer.parseInt(enteredString.trim()); //then cast as a integer
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e) {
System.out.println("Your entry: \"" + enteredString + "\" is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError == true ); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
You are doing simple things in a complex way, however, my code can still be replaced by a compressed version but you can understand this better. Following code is doing exactly what you want it to do. I've:
Created Player class, so each player will keep record of guessedNumbers, Number of Guesses and it's name.
You don't have to make tons of variables like pName[], play, validGuesses etc...
I have changed some of the If-Conditions and removed the outer while-loop
Added new round concept, so whenever a player guessed the number, the number got changed.
and much more ....
UPDATED Code: Now each Player has a different random number to guess.
import java.util.*;
public class GuessNumber
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
Random myRand = new Random();
ArrayList<Player> players = new ArrayList<Player>();
int x = 0;
System.out.println("how many players are there?:");
int noPlayer = checkint();
boolean validGuess = true , playError = true;
for (int i = 0; i<noPlayer; i++)
{
System.out.println("New player, what is your name?:");
players.add(new Player (keyboard.nextLine()));
}
for (int i = 0; i<noPlayer; i++)
{
players.get(i).number = myRand.nextInt(100) + 1;
}
int i =0; // for chossing different player each time
do
{
System.out.printf(players.get(i).name + " enter what you think the number is between 0 and 100!: ");
x= checkint();
players.get(i).guessedNumbers.add(x);
players.get(i).numOfGuesses++;
if (x == players.get(i).number)
{
System.out.println("That's correct!");
System.out.println("It took you " + players.get(i).numOfGuesses + " tries!");
System.out.print("These are all the numbers you guessed: ");
System.out.println(players.get(i).guessedNumbers);
do
{
System.out.println("Would you like to play again: Yes or No");
String answer = keyboard.nextLine();
if (answer.compareToIgnoreCase("yes") == 0)
{
playError = false;
players.get(i).number = myRand.nextInt(100) + 1; // creates a new random number for second round of the game
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
}
else if (answer.compareToIgnoreCase("no") == 0)
{
playError = false;
System.out.println("Thank you for playing");
System.out.println("\n\n************ " +players.get(i).name + " WON ********");
System.out.println("\n************* SECOND ROUND STARTS **********");
players.remove(i);
}
else
{
System.out.println("You answer was invalid");
playError = true;
}
} while (playError);
}
else if (x>players.get(i).number)
System.out.println("Lower than that!");
else if (x<players.get(i).number)
System.out.println("Higher than that!");
if(i == noPlayer-1 || !(playError))
i = 0;
else
i++;
}while (players.size() > 0);
System.out.println("\n\n******************** Every Body Guessed Their Numbers ******************");
}
static int checkint()
{
int enteredNumber = 0;
Scanner myScanner = new Scanner(System.in);
boolean numberError = false;
do
{
try
{
enteredNumber = Integer.parseInt(myScanner.next().trim());
if (enteredNumber < 0 || enteredNumber > 100)
{
System.out.println("Either you entered a negative number or number is above the random number generator range");
numberError = true;
}
else
numberError = false; //if we haven't bailed out, then the number must be valid.
} catch(Exception e)
{
System.out.println("Your entry is invalid...Please try again");
numberError = true; //Uh-Oh...We have a problem.
}
} while (numberError); //Keep asking the user until the correct number is entered.
return enteredNumber;
}
}
// now each player would have its own record.
class Player
{
int numOfGuesses= 0;
ArrayList<Integer> guessedNumbers = new ArrayList<Integer>();
String name = "";
int number = 0;
public Player(String nam)
{
name = nam;
}
}
NOTE: I've added some new lines to output on the screen , once a players wins and want to play again or not. I recommend you to compare your code with mine, so that you'll get a better understanding of your approach vs mine. Do let me know if you find something difficult to understand.
Just use the Random class:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
I referenced here.
How do I generate random integers within a specific range in Java?

Why is my do-while loop not working?

When I compile, that try to enter (y) to play again my do - while is not working, it takes me out of the loop.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
int guessNumber = 0;
do
{
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
}
Change the code as below: (You just need to update the variables inside the loop)
public static void main(String[] args) {
// Creating a play again variable
String playAgain = "";
// Create Scanner object
Scanner scan = new Scanner(System.in);
// Create a random number for the user to guess
int theNumber = 0;
int guessNumber = 0;
do
{
// new lines to be added
theNumber = (int)(Math.random() * 100 + 1);
guessNumber = 0;
System.out.println("Guess a number between 1 - 100: ");
while (guessNumber != theNumber)
{
guessNumber = scan.nextInt();
if (guessNumber > theNumber)
{
System.out.println("Sorry, try again too high!");
}
else if (guessNumber < theNumber)
{
System.out.println("Sorry, try again too low!");
}
else
{
System.out.println("Congrats, you got it!");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye.");
scan.close();
}
Here is the execution of code on Jshell:
The reason the program is not working is because the do-while loop does one iteration before it gets to the "while" part. In your case, the program successfully finishes the loop after a user correctly guesses the number. Your program breaks because after that you are requiring the user to enter 'y' to continue endlessly without letting them guess a number. If they guess a number, the program terminates.

Play Again feature not working

I can't seem to be able have my program ask the user if they would like to play again. The program ends when asking if they would like to continue. I added a break because before the program was continuously looping the correct answer and number of tries.
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
A few things with your program.
As the comments have noted, you do need to flush your new-line character after using nextInt().
But, you must also set the guess value and try-count back to 0 after the user states that they would like to play again -- otherwise the program will just continue in a "You win!" loop.
I would recommend moving your variable declarations to the outer loop:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}

Categories

Resources