Why is this While Loop not executing properly - java

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

Related

How to write a while loop

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();
}

Coin Toss JavaScript with user input

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.");
}
}
}
}
}

Basketball simulator keeps executing?

My friend tried asking this question earlier and wasn't specific enough, so I'll try being a bit more detailed. We're trying to make a basketball simulator between two players that keeps playing until one player has reached 21 points, and then stops. We got fairly far, and while the program runs, it continues executing, instead of ending at 21 points for one player, and keeps running until I believe the program crashes. Does anyone have any idea on what needs to be added to prevent the program from executing after 21 points for one of the two players? I will post the code below, and if you would like a screenshot of the output, I would be happy to provide one. Thank you!
Code:
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Formatter;
import java.util.Scanner;
import java.util.Random;
public class KobeVsLebron {
//VARIABLES
public Random randomGenerator;
private static int kscore = 0;
private static int lscore = 0;
//declare scanner
static Scanner input = new Scanner(System.in);
//main method
public static void main(String[] arguments) {
System.out.println("\n Welcome to Kobe vs Lebron Simulation");
System.out.println("In this simulation you will have a choice to flip a coin.");
System.out.println("Whatever the outcome of the flip is the starting players ball.");
System.out.println("The simulation is based off of a long standing argument");
System.out.println(" Kobe Bryant vs Lebron James in a game of 21.");
MainMenu();
}
/*******************************************************************************/
METHODS
//Main Menu
//PlayKobe
//PlayLebron
//LeaderBoard();
//ReadFile();
//WriteFile();
//Win();
private static void MainMenu(){
char choice;
do {
System.out.println("\nTo the run the simulation flip the coin by choosing 'F', \nTo print the leaderboard enter 'L' \nTo quit enter 'Q'");
choice = input.next().charAt(0);
switch (choice) {
case 'F':
case 'f':
FlipCoin();
break;
case 'L':
case 'l':
// LeaderBoard();
break;
case 'Q':
case 'q':
default:
System.out.println("Invalid Choice! TRY AGAIN!");
}
}
while (choice != 'Q');
}
private static void FlipCoin() {
Random randomGenerator;
int sides;
int currentsides;
System.out.printf("\nThe coin will be flipped heads(Kobe) or tails(Lebron)");
randomGenerator = new Random(); //initialize random object
sides = 2; //default number of sides
currentsides = randomGenerator.nextInt(sides)+1; //initialize roll (1-2)
System.out.printf("\nThe coin is being flipped.....");
//TIME DELAY '1000 is one second'
try {
Thread.sleep(1500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
if(currentsides == 1 ){
System.out.printf("\nThe coin has been flipped to heads. \nKobe has the ball.");
PlayKobe();
}
if(currentsides == 2){
System.out.printf("\nThe coin has been flipped to tails. \nLebron has the ball.");
PlayLebron();
}
}
private static void PlayKobe() {
Random randomGenerator;
int shot;
//int kscore = 0;
int shotclock;
if(kscore < 22){
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nKobe drives in to the basket");
System.out.printf("\nLebron on his tail!");
System.out.printf("\nKobe scores the lay-up! and thats two for Kobe! ");
kscore += 2;
PlayLebron();
}
if(shotclock == 2){
System.out.printf("\nKobe dribbles towards the line ");
System.out.printf("\nLebron has him covered, Kobe takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Kobe!");
kscore += 3;
PlayLebron();
}
if(shotclock == 3){
System.out.printf("\nKobe is locked down and shaking!");
System.out.printf("\nLebron Steals the ball! ");
PlayLebron();
}
}
private static void PlayLebron(){
Random randomGenerator;
int shot;
// int lscore = 0;
int shotclock;
if(lscore < 22){
System.out.printf("\nLerbon has won the game of 21!");
//Win();
}
randomGenerator = new Random(); //initialize random object
shot = 3; //default number of sides
shotclock = randomGenerator.nextInt(shot)+1; //initialize roll (1-2)
if(shotclock == 1){
System.out.printf("\nLebron drives in to the basket");
System.out.printf("\nKobe on his tail!");
System.out.printf("\nLebron scores the lay-up! and thats two for Lebron!");
lscore += 2;
PlayKobe();
}
if(shotclock == 2){
System.out.printf("\nLebron dribbles towards the line ");
System.out.printf("\nKobe has him covered, Lebron takes the fade away shot!");
System.out.printf("\nScore! thats 3 points for Lebron!");
lscore += 3;
PlayKobe();
}
if(shotclock == 3){
System.out.printf("\nLebron is locked down and shaking!");
System.out.printf("\nKobe Steals the ball! ");
PlayKobe();
}
}
}
Currently you have
if(kscore < 22) {
System.out.printf("\nKobe has won the game of 21!");
//Win();
}
Which essentially means your code does nothing besides printing when a player reaches the score limit, you want to add a return statement to go back to your main loop.
You'll also want to check for when the score exceeds 21 and not the opposite.
if(kscore > 21) {
System.out.printf("\nKobe has won the game of 21!");
return;
}
You'll need that for both players ofc.

I need to end Game over or continue While loop for class

For my class we need to make a dice game, I made I version of war, I need a little help finishing it. I need to Display the final points and I would like it if somehow I could display the difference between the scores. I also do not know how to end the game over loop.
public class Game {
public static void main(String[] args)
{
Dice myDie = new Dice();
Dice CompDie= new Dice();
int player =0;
int computer =0;
boolean gameOver;
do
{
int[] scores = new int[3];
gameOver = false;
while(!gameOver)
{
myDie.roll();
System.out.println("You rolled a " + myDie.getValue());
player = myDie.getValue();
CompDie.roll();
System.out.println("Computer rolled a " + CompDie.getValue());
computer = CompDie.getValue();
checkResults(player, computer, scores);
printResults(scores);
// ask player if want to continue enter Y to continue
System.out.println("Do you want to continue playing enter Y if so"); // I need to end loop here
}
}while(keepPlaying());
}
public static boolean keepPlaying()
{
Scanner readIn = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Do you want to play again?");
String answer = readIn.nextLine().toUpperCase();
char ans = answer.charAt(0);
if(ans == 'Y')
playAgain = true;
return playAgain;
}
public static void checkResults(int player, int computer, int[] scores)
{
if(player > computer)
{
scores[1]++;
}
else if(player < computer)
{
scores[2]++;
}
else
{
scores[0]++;
}
}
public static void printResults(int[] list)
{
System.out.println(" Ties Player Computer");
for (int i = 0; i < list.length; i++)
{
System.out.printf("%8d", list[i]);
}
System.out.println();
}
}
while(!gameOver)
{
}
This loop is unnecessary and also never stops. If you still want it you need to set gameOver = true when you want to quit.
To show the difference between scores just subtract scores from each other and print it. System.out.println(Math.abs(score[1] - score[2]));
Something like this.

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