I am writing a simple craps simulator for Java class and for some reason, it is having trouble running correctly. It is supposed to keep track of losses with "point" and wins with "point" but for some reason, those values tend to be 1 or 0 everytime. The losses and wins on first roll seem to be working. Wondering if someone with a fresh set of eyes can figure out where I messed up. Thank you!
import java.util.Scanner;
import java.util.Random;
class CrapsSimulator {
public static void main(String[] args) {
// Set up values we will use
int lossfirstroll = 0;
int winfirstroll = 0;
int losswithpoint = 0;
int winwithpoint = 0;
boolean gameover = false;
int point = 0;
// Loop through a craps game 100 times
for (int i = 0; i < 100; i++) {
// First roll -- random number within 2-12
Random rand = new Random();
int random = rand.nextInt(11) + 2;
// Win on first roll
if (random == 7 || random == 11) {
winfirstroll++;
gameover = true;
} // Loss on first roll
else if (random == 2 || random == 3 || random == 12) {
lossfirstroll++;
gameover = true;
} else // Player has "point"
{
point = random;
}
// Check to make sure the game hasn't ended already
while (gameover == false) {
// Reroll the dice
random = rand.nextInt(11) + 2;
// Check to see if player has won
if (random == point) {
winwithpoint++;
gameover = true;
}
// Or if the player has lost
if (random == 7) {
losswithpoint++;
gameover = true;
}
// Otherwise, keep playing
gameover = false;
}
}
// Output the final statistics
System.out.println("Final Statistics\n");
System.out.println("Games played: 100\n");
System.out.println("Wins on first roll: " + winfirstroll + "\n");
System.out.println("Losses on first roll: " + lossfirstroll + "\n");
System.out.println("Wins with point: " + winwithpoint + "\n");
System.out.println("Losses with point: " + losswithpoint + "\n");
}
}
either run it through a debugger, or sprinkle System.out.println and see where your logic is failing. Is this homework?
Your problem is the gameover flag. You are always settings it to false again at the end of the inner loop, this will make it run forever.
Related
So I'm writing some code for a card game and within this card game I have coded how the first round works. My question is how I would be able to repeat this code over and over again until the cards run out( since each card can only be used once). I'm thinking that I have to use a while loop. For convenience I will explain what each of the methods here do so that you may understand, so please bear with me. Some of this is useless code that I haven't gotten to complete yet and make useful.3
The rules to the game : https://tobakumokushirokukaiji.fandom.com/wiki/E_Card
** Here are the methods : **
typeOfCard(); - this tells you which side you are playing on and is decided randomly, so far you can only play on the Emperor side.
winOrLose() - this is the last method i worked on before making this post, this is what I am trying to implement to allow me to replace the current win or loss output as strings which i can call easier than print statements. I want to make this so that the games which are won can set the int wincounter to 1 so it can print this out.
emperorsTurn() - this is the method that asks the main questions of which card you would like to play versus the computer.
wincounter() - some code i need to delete so dont worry about this
import java.util.Random;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args) {
int numberOfCards = 7;
if (numberOfCards > 6) {
numberOfCards--;
//System.out.println("your number of cards is " +numberOfCards);
}
typeOfCard();
}
public static void typeOfCard() {
Random card = new Random();
int number = 0;
for (int counter =1; counter <=3;counter++){
number = 1+card.nextInt(2); }
if (number == 1) {
System.out.println("your are playing on the emperor side");
}
if (number ==2){
System.out.println("You are playing on the slave side ");
}
if (number ==1){
emperorsTurn();
}
}
public static void winOrLose(){
int wincounter = 0;
String win = "You won the round";
String lose = "You lose the round ";
if (wincounter >0) {
System.out.println(win);
}
else if (wincounter == 0) {
System.out.print(lose);
}
}
public static void emperorsTurn() {
Random cards = new Random();
int computerinput = 0;
for (int counter = 1; counter <= 3; counter++) {
computerinput = 1 + cards.nextInt(2);
}
Scanner sc = new Scanner(System.in);
System.out.println("Please pick the card you are playing. \n if you are playing the Emperor press 1, if you are playing the citizen press 2 ");
int userinput = sc.nextInt();
if (userinput == 1 && computerinput == 1) {
System.out.println("you have played the emperor! \n the emperor is defeated by the slave");
}
else if (userinput ==1 && computerinput ==2) {
System.out.println("you have played the emperor the emperor defeats the citizen");
winOrLose();
wincounter();
}
else if (userinput == 2) { //when the user input is 2
if (computerinput == 1) {
System.out.println("you have played the citizen, this defeats the slave");
wincounter();
} else if (computerinput == 2) {
System.out.println("you have played the citizen, this ties with the citizen");
}
//print out something else if number is not 1,2 or 3
}
}
public static void wincounter() {
int i = 0;
if (i < 1)i++;
System.out.println("you have won " +i +" number of draws");
}
}
Try doing a while loop that compares the number of cards left to the minimum number needed to play a game.
while (numberOfCards > minNumberNeeded) {
playGame();
}
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?
This program is an attempt at making a similar game to Battleships on the command line. If my program takes 3 inputs that are "HITS" it terminates. Why is this? My suspicion is that there is something wrong with my logic in the if/else statements.
The reason I have 3 lists is because I want to let the user know that they have hit 3 consecutive numbers and that they have sunk a ship in the game. Also, I am aware of the potential problem that can occur when the random method generates the same number in more than one list.
Apologies if the code is not written very nicely. I am still a beginner.
Main
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static int numOfHits = 0;
public static int numOfGuesses = 0;
public static int userInput;
public static int number;
public static void main(String[] args) {
Game a = new Game();
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> hitlist = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> list3 = new ArrayList<Integer>();
int temp = a.numGenerator();
list.add(temp);
list.add(temp+ 1);
list.add(temp + 2);
int temp2 = a.numGenerator();
list2.add(temp2);
list2.add(temp2 + 1);
list2.add(temp2 + 2);
int temp3 = a.numGenerator();
list3.add(temp3);
list3.add(temp3 + 1);
list3.add(temp3 + 2);
System.out.println(list + " " + list2 + " " + list3);
Scanner input = new Scanner(System.in);
System.out.println("Welcome to BattleShips! In this version; the game is on a long 30 cell row and there are 3 different sub rows to kill. Input your guesses.");
while(!input.hasNextInt()) {
System.out.println("That is not an integer. Please try again.");
input.next();
}
while(list.isEmpty() == false && list2.isEmpty() == false && list3.isEmpty() == false) {
while(!input.hasNextInt()) {
System.out.println("That is not an integer or the number is too large to be stored as an integer. Please try again.");
input.next();
}
userInput = input.nextInt();
while(hitlist.contains(userInput)) {
System.out.println("You have already hit that one! Try again.");
userInput = input.nextInt();
}
while(true) {
if(list.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list.indexOf(userInput);
hitlist.add(userInput);
list.remove(index);
System.out.println("HIT!");
userInput = -100;
break;
}
if(list2.contains(userInput) && !list.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list2.indexOf(userInput);
hitlist.add(userInput);
list2.remove(index);
System.out.println("HIT!");
break;
}
if(list3.contains(userInput)) {
numOfGuesses++;
numOfHits++;
int index = list2.indexOf(userInput);
hitlist.add(userInput);
list3.remove(index);
System.out.println("HIT!");
break;
}
else {
numOfGuesses++;
System.out.println("MISS!");
}
}
if(numOfHits == 9) {
System.out.println("Congratulations! You have beaten the game.");
System.out.println("You took " + numOfGuesses + " guesses");
System.exit(0);
}
}
}
}
Game
import java.util.ArrayList;
public class Game {
private double randomNumber;
public int numGenerator() {
randomNumber = Math.random() * 30 + 1;
return (int) randomNumber;
}
}
The bug
I do not get a compiler error. It is a logic error. Here is an example:
[15, 16, 17] [8, 9, 10] [28, 29, 30] // NUMBERS GENERATED FROM MATH.RANDOM
Welcome to BattleShips! In this version; the game is on a long 30 cell row and there are 3 different sub rows to kill. Input your guesses.
15
HIT!
15
You have already hit that one! Try again.
16
HIT!
17
HIT!
//AFTER THIS LINE IT TERMINATES. I WANT THE USER TO KEEP MAKING GUESSES UNTIL 9 NUMBERS ARE HIT.
The problem is in your while condition:
while(list.isEmpty() == false && list2.isEmpty() == false && list3.isEmpty() == false)
It checks till any one of the lists is not empty.
Change it to:
while(list.isEmpty() == false || list2.isEmpty() == false || list3.isEmpty() == false) {
This will check till all of the lists are not empty.
When I run this code, which is a menu with many different options. it consists of many loops. Some of which I have yet to make. But my issue arises when I have the user select "t" or the coin toss simulator. The loop begins but once the user enters the amount of coin flips say 4, it says 2.0 heads and 2.0 tails means 50.0% were heads
Type code letter for your choice: COIN TOSS SIMULATOR
Enter 0 to quit. How many tosses?
It shouldn't say type the letter for your choice: COIN TOSS SIMULATOR, enter 0 to quit. how many tosses?
Also when I enter 0 it says You have entered an invalid option. 't' is not a valid option. I want to Bring back the main menu!!!! what is going on????
public class toolBox {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
boolean properInput = false;
int usersInput;
while (!properInput) {
System.out.println("Enter seed value:");
if (myScanner.hasNextInt()) {
usersInput = myScanner.nextInt();
properInput = true;
Random randomSeed = new Random(usersInput);
String randomNumberList = "";
for (int i = 0; i < 10; i++) {
randomNumberList += randomSeed.nextInt(80) + " ";
}
} else
{
String helloWorld = myScanner.next();
System.out.println("You have not entered an integer. '" + helloWorld + "' is not an integer");
}
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{
Scanner anotherScanner = new Scanner(System.in);
boolean usersSelection = false;
String c;
outer:
while (!usersSelection) {
{
System.out.print("" + "Type code letter for your choice: ");
}
if (anotherScanner.hasNext("q|Q")) {
c = anotherScanner.next();
usersSelection = true;
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
{
System.out.println("" + "COIN TOSS SIMULATOR" + "");
}
System.out.println("Enter 0 to quit. How many tosses?");
Random rand = new Random();
boolean headsOrTails;
float headsCount = 0;
float tailsCount = 0;
Scanner scanMan = new Scanner(System.in);
int numero = scanMan.nextInt();
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
headsOrTails = rand.nextBoolean();
if (headsOrTails == true) {
headsCount++;
} else {
tailsCount++;
}
}
System.out.println(headsCount + " heads and " + tailsCount + " tails means "
+ (headsCount / (headsCount + tailsCount) * 100 + "% were heads"));
}
}
if (anotherScanner.hasNext("g|G")) // if the user were to enter either case of g, the
// program will register both and initialize the
// grade estimator.
{
c = anotherScanner.next();
usersSelection = true;
}
if (anotherScanner.hasNext("c|C"))
{
c = anotherScanner.next();
usersSelection = true;
System.out.println("Welcome to the Color Challenge!");
}
else {
String zoom = anotherScanner.next();
System.out.println("You have entered an invalid option. '" + zoom + "' is not a valid option.");
}
}
}
}
Your question is not clear, but your title suggests to me you think there is an inner and outer loop.
You don't have an inner and an outer loop.
Your indentation was really messy, but when I cleaned it up and then deleted a lot of extra lines of code, the structure of the code became clear.
Notice the following:
1) You have two loops, one on top switched on !properInput, the lower one switched on !usersSelection. There is also a for loop, but it doesn't do anything related to the code flow you are asking about.
2) You have two identical labels, one outside an anonymous block of code (see my comment in the code below), and another inside the anonymous block. In this case it doesn't affect your question, but it is definitely a problem.
My guess is that your break outer line isn't working because you are breaking out of the lower while loop.
I suggest you try fragmenting your code into functions to make the structure clearer.
while (!properInput) {
}
outer:
System.out.println("===== CS302 TOOL BOX =====\nT > COIN TOSS SIMULATOR\nG > GRADE ESTIMATOR\nC > COLOR CHALLENGE\nQ > QUIT");
{ /* begin anonymous code block */
outer:
while (!usersSelection) {
if (anotherScanner.hasNext("q|Q")) {
System.out.println("" + "" + "Good-Bye");
break;
}
if (anotherScanner.hasNext("t|T")) {
System.out.println("Enter 0 to quit. How many tosses?");
if (numero == 0) {
break outer;
}
for (int j = 0; j < numero; j++) {
}
}
}
}
I'm trying to do roshambo (or Rock-Paper-Scissors) and have the computer output Rock, Paper, or Scissors in place of a random value from 0 to 2. However, I'm not getting random values. When the program runs it goes through a while loop, and each time it goes through the loop, the value remains the same. However, if I stop, then re-run the application, the value changes, and remains that same value for the duration of the loop. Am I coding this method correctly?
public class Player2 extends Player{
private Random rand;
public Player2(){
rand = new Random();
}
public Roshambo generateRoshambo() {
int min = 0;
int max = 2;
int randomNum = rand.nextInt(max - min + 1) + min;
if(randomNum == 0){
return Roshambo.ROCK;
} else if (randomNum == 1) {
return Roshambo.PAPER;
} else {
return Roshambo.SCISSORS;
}
}
}
Here is the loop:
Roshambo value = p2.generateRoshambo();
String cont = "Yes";
do{
System.out.print("\nRock, Paper, or Scissors: ");
String choice = sc.nextLine();
System.out.println("\n" + name + ": " + choice);
System.out.println("Computer: " + value);
if (value == ...)
{
System.out.println("\n" + name + " Wins!\n");
}
else if (value == ...)
{
System.out.println("\nYou Tied!\n");
}
else
{
System.out.println("\nThe Computer Wins!\n");
}
System.out.print("Play again? (Yes/No): ");
cont = sc.nextLine();
} while (cont.equalsIgnoreCase("Yes"));
I just realized my own mistake. I called p2.generateRoshambo() outside of my do-while loop. By putting the following in my loop, I was able to solve the problem:
Roshambo value = p2.generateRoshambo()
The most likely cause of the symptom is creating a new Random instance each time round. The default seed is based on a clock that may not have ticked in a tight loop. It is important to create as few Random instances a possible, usually only one in a program, and go on getting values from it.