Why is my program looping twice more than needed? - java

I am completely new to programming and I was making a program for class. For the project, I need to make a "self directed" program. I wanted to make a simple program; I wanted a fighting simulator! So the point of the program is to do this:
Introduce you, and start the fight. The attack is completely random out of 5, and you and the "enemy" fight until one of you hits 0 hp. I want the program to end, and display the health of you and your enemy and tell you if you have won or not. Pretty simple, but it's harder than you'd think especially with the lack of programming I have learned. I just need help fixing it or simplifying it. Thanks for the information if you can help! Code below:
import java.util.Scanner;
public class TG_UN4EX13 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String rumble = "startvalue";
System.out.println("Welcome to the Ultimate Battle Game!");
System.out.println("Have Fun!");
// Attack Section //
int attack1 = 5;
int attack2 = 10;
int attack3 = 20;
int attack4 = 40;
int cower = 0;
// Character Section//
int playerhealth = 100;
// Character Section//
// Enemy Section//
int enemyhealth = 100;
// Enemy Section//
while (playerhealth >= 0 || enemyhealth >= 0 || rumble.equalsIgnoreCase("Yes")) {
int attacknumber = (int) (Math.random() * (5 - 1 + 1) + 1);
int attacknumber2 = (int) (Math.random() * (5 - 1 + 1) + 1);
if (attacknumber == 1) {
enemyhealth = enemyhealth - attack1;
System.out.println("You used Punch!");
System.out.println("You did " + attack1 + " damage! \n");
} else if (attacknumber == 2) {
enemyhealth = enemyhealth - attack2;
System.out.println("You used Kick!");
System.out.println("You did " + attack2 + " damage! \n");
} else if (attacknumber == 3) {
enemyhealth = enemyhealth - attack3;
System.out.println("You used Jab!");
System.out.println("You did" + attack3 + " damage! \n");
} else if (attacknumber == 4) {
enemyhealth = enemyhealth - attack4;
System.out.println("You used Roundhouse Kick!");
System.out.println("You did " + attack4 + " damage! \n");
} else if (attacknumber == 5) {
enemyhealth = enemyhealth - cower;
System.out.println("You cowered in fear!");
System.out.println("You did " + cower + " damage! \n");
}
if (attacknumber2 == 1) {
playerhealth = playerhealth - attack1;
System.out.println("They used Punch!");
System.out.println("They did " + attack1 + " damage! \n");
} else if (attacknumber2 == 2) {
playerhealth = playerhealth - attack2;
System.out.println("They used Kick!");
System.out.println("They did " + attack2 + " damage! \n");
} else if (attacknumber2 == 3) {
playerhealth = playerhealth - attack3;
System.out.println("They used Jab!");
System.out.println("They did " + attack3 + " damage! \n");
} else if (attacknumber2 == 4) {
playerhealth = playerhealth - attack4;
System.out.println("They used Roundhouse Kick!");
System.out.println("They did " + attack4 + " damage! \n");
} else if (attacknumber2 == 5) {
playerhealth = playerhealth - cower;
System.out.println("They cowered in fear!");
System.out.println("They did " + cower + " damage! \n");
}
System.out.println("You have " + playerhealth + " health!");
System.out.println("They have " + enemyhealth + " health! \n");
}
if (playerhealth > enemyhealth) {
System.out.println("You won!");
System.out.println("Do you want to play again?");
rumble = scan.nextLine();
} else {
System.out.println("You lost!");
System.out.println("Do you want to play again?");
rumble = scan.nextLine();
}
if (rumble.equalsIgnoreCase("no")) {
System.out.println("Well, goodbye!");
System.exit(0);
}
}
}
P.S. This is a quick edit but here is an example:
You have 20 health! They have 20 health!
You used Jab! You did20 damage!
They used Roundhouse Kick! They did 40 damage!
You have -20 health! They have 0 health!
You used Jab! You did20 damage!
They used Roundhouse Kick! They did 40 damage!
You have -60 health! They have -20 health!
You lost! Do you want to play again?

I'm not positive, but I think you may need to change:
while(playerhealth>=0 || enemyhealth>=0 || rumble.equalsIgnoreCase("Yes"))
to
while((playerhealth>0 && enemyhealth>0) || rumble.equalsIgnoreCase("Yes"))
If the health is =0, it will run again, so remove the = as well

Take a look at the conditions for your loop.
while (playerhealth >= 0 || enemyhealth >= 0 || rumble.equalsIgnoreCase("Yes")) {
//do stuff
}
You're saying, "Keep fighting while any of the following conditions are true":
Player health is positive
Enemy health is positive
Rumble = Yes
Now think about what it will take to exit that loop (ie, end the game).
Exiting the loop is the opposite of staying in the loop, so you want the opposite of those conditions, which is, "Stop fighting when all of the following are true":
Player health is less than 0
Enemy health is less than 0
Rumble != Yes
Do you mean for the fight to only end when both the player and enemy have negative health, or should it end when either the player or the enemy have negative health?

Related

&& and || in while loop problems

I have been assigned to make a dice game of high or low for my intro to java course. I have all the methods completed, however, I need to use a while loop so that I can continue to play the game until my cash hits 0 or if I bet 0 dollars. I do not want to use a break if I do not have to. So my question is what can I do (if possible) to just only use the while loop? Here is my program:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int cash = 100;
int bet = 1
while(cash > 0 || bet != 0)
{
bet = getBet(in, cash);
char choice = getHighLow(in);
int roll1 = getRoll();
System.out.println("Dice 1 rolls: " + roll1);
int roll2 = getRoll();
System.out.println("Dice 2 rolls: " + roll2);
int total = (roll1 + roll2);
System.out.println("The total roll is: " + total);
int winnings = determineWinnings(choice, bet, total);
cash = cash + winnings;
}
System.out.println("You have " + cash + " dollars left. Goodbye!");
}
// Given a Scanner and a current maximum amount of money, prompt the user for
// an integer representing the number of dollars that they want to bet. This
// number must be between 0 and to maximum number of dollars. If the user enters
// a number that is out of bounds, display an error message and ask again.
// Return the bet to the calling program.
private static int getBet(Scanner inScanner, int currentPool) {
System.out.println("You have " + currentPool + " dollars");
System.out.println("Enter and amount to bet (0 to quit): ");
int bet = inScanner.nextInt();
while (0 > bet || currentPool < bet )
{
System.out.println("Your bet must be between 0 and " + currentPool + " dollars ");
bet = inScanner.nextInt();
}
return bet;
}
// Given a Scanner, prompt the user for a single character indicating whether they
// would like to bet High ('H'), Low ('L') or Sevens ('S'). Your code should accept
// either capital or lowercase answers, but should display an error if the user attempts
// to enter anything but one of these 3 values and prompt for a valid answer.
// Return the character to the calling program.
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
inScanner.nextLine();
char choice = inScanner.nextLine().charAt(0);
choice = Character.toUpperCase(choice);
while (choice != 'H' && choice != 'L' && choice != 'S')
{
System.out.println("You must choose between high, low or sevens (H/L/S): ");
choice = Character.toUpperCase(inScanner.nextLine().charAt(0));
}
return choice;
}
// Produce a random roll of a single six-sided die and return that value to the calling
// program
private static int getRoll() {
Random generate = new Random();
int roll = generate.nextInt(6) + 1;
return roll;
}
// Given the choice of high, low or sevens, the player's bet and the total result of
// the roll of the dice, determine how much the player has won. If the player loses
// the bet then winnings should be negative. If the player wins, the winnings should
// be equal to the bet if the choice is High or Low and 4 times the bet if the choice
// was Sevens. Return the winnings to the calling program.
private static int determineWinnings(char highLow, int bet, int roll) {
if(roll <= 6)
{
if(highLow == 'L')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
else if (roll == 7)
{
if(highLow == 'S')
{
System.out.println("You won " + (bet * 4) + " dollars! ");
return (bet * 4);
}
else
System.out.println("You lose! ");
return -bet;
}
else
{
if(highLow == 'H')
{
System.out.println("You won " + bet + " dollars! ");
return bet;
}
else
System.out.println("You lose! ");
return -bet;
}
}
}
Change the while(cash > 0 || bet != 0) to while(cash > 0 && bet != 0)
This is because, you want to end the game if either cash equals 0 or when bet equals 0. If you use the || then only when both variables are 0 will the loop stop. If you use the && then the loop will stop if either of the variables are 0.
when && is used, both conditions must be true for the loop to execute. If one condition is true and the other is false then, the loop will stop.
when || is used, any one
condition must be true for the loop to execute. If both conditions are true the the loop will run. If one of the conditions is false and the other is true then, it will still run. If both conditions are false then, the loop will stop.
EDIT:
If you want the program to end as soon as the bet variable is 0 then just add these lines after bet = getBet(in, cash);:
if(bet<=0){
System.out.println("You are out of cash!");
break;
}
Hope this helped:)

trying to understand my error in my pig java game

I am working on my final project for my intro to java class and i am having a hard time understanding the errors in my project and why it will not run if you could tell me why i would greatly appreciate it
public static void main(String[] args) {
Scanner scanner1;
int dice, dice2;
int pScore, cScore = 0;
int pTotalScore = 0;
int cTotalScore = 0;
final int maxScore = 750;
String input = "R";
String input2 = "R";
char repeat;
Random randomNumbers = new Random();
System.out.println("Welcome to Our version of the dice game Pig");
System.out.println("Here are the instructions");
System.out.println("On a turn, the player or computer rolls the die repeatedly");
System.out.println("Until either a 1,7,12, or 17 is rolled");
System.out.println("or the player or computer holds");
System.out.println("If a 1,7,12, or 17 is rolled, that player's turn ends");
System.out.println("and no points are earned");
System.out.println("If the player chooses to hold, all of the points rolled during");
System.out.println("that turn are added to his or her score.");
System.out.println("First player to 750 points or more WINS!");
System.out.print("\nPlease enter your name: ");
scanner1 = new Scanner(System.in);
String pName = scanner1.nextLine();
System.out.print("\nI Hope You have fun," + pName);
do { // run at least once. Start of loop
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.printf("%s you rolled a %d %n", pName, dice);
if (dice == 1 || dice == 7 || dice == 12 || dice == 17) // if these numbers, end
{
pScore = 0;
System.out.println("Turn over.");
System.out.println(" " + pName + " total is " + pScore + " ");
break;
} else { // else ask for re-roll
pScore = dice;
pTotalScore += pScore;
System.out.print(+pScore + " Your turn total is " + pTotalScore + " ");
System.out.print("Enter (R) to roll or (H)to hold: ");
input = scanner1.nextLine();
repeat = input.charAt(0);
}
if (repeat != 'R') { // if something other than R, end
break;
}
} while (pTotalScore < 750 || cTotalScore < 750); // allow repeat so long as scores are less than 750
if (repeat == 'H') {
System.out.println("Turn over.");
System.out.print("Current score: " + pname + " has " + pTotalScore);
System.out.println("The Computer has " + cTotalScore);
break;
}
while (input.equalsIgnoreCase("R"));
if (pTotalScore >= maxScore) {
System.out.println("Your total Score is " + totalScore);
System.out.println(+pname + "WINS!");
break;
}
System.out.println();
System.out.println("It is the Computer's turn.");
do {
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The Computer rolled: " + dice2);
if (dice2 == 1 || dice2 == 7 || dice2 == 12 || dice2 == 17) {
cScore = 0;
System.out.print("Turn over");
System.out.println("The Computer total is " + cTotalScore);
break;
} else {
cScore = dice2;
cTotalScore += cScore;
System.out.print("The Computer's total is " + cTotalScore + " ");
System.out.print("Enter (r) to Roll or (H)to Hold: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
}
if (repeat == 'H') {
System.out.println("Turn over");
System.out.print("Current score:" + pName + " has " + pTotalScore);
System.out.println(", The Computer has " + cTotalScore);
break;
}
} while (input2.equalsIgnoreCase("R"));
if (cTotalScore >= maxScore) {
System.out.println("The Computer's score is " + cTotalScore + "\n");
System.out.println("The Computer wins!!!!");
System.out.printl("Run The uprisng has begun!!!!!!");
break;
}
Final3.java:112: error: reached end of file while parsing } ^ 1 error
now the problem is i get the error basically means im missing a } but i cant see where it would be nd no matter where i put it it still says
Final3.java:112: error: reached end of file while parsing } ^ 1 error
You have one while loop that does nothing - while (input.equalsIgnoreCase("R")); - and you didn't close your main method. Add } at the end.
Add a closing brace "}" in the end.I hope this will solve your purpose.

Loop and conditionals not working properly [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
If I do not roll a 1, and I would like to "hold" my roll. The code ignores the instructions within the "h" bracket conditional statement, and rolls the dice again. I am confused because if I do roll a 1, the code does work and goes to the computer's turn, setting the flags correctly.
while ((humanScore <= 100) && (computerScore <=100))
{
/*loop while human turn is true*/
while ((humanTurn == true) && (computerTurn == false))
{
die = randomGenerator.nextInt(6) + 1;
if(die == 1)
{
System.out.println("Human, you rolled a 1, you lose your points and your turn.");
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("Your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}
else if(die != 1)
{
System.out.println("Human, you currently have " + points + " points to add to score.");
System.out.println("You have rolled a " + die + " would you like to hold, or roll again?");
System.out.println("Please enter either r to roll, or h to hold.");
points = points + die;
decision = scanner.next();
if (decision == "r")
{
humanTurn = true;
}
if(decision == "h")
{
humanScore = humanScore + points;
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("You hold, your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}
}
}
if (decision.equals("r"))
{
humanTurn = true;
}
if(decision.equals("h"))
{
humanScore = humanScore + points;
humanTurn = false;
computerTurn = true;
points = 0;
System.out.println("You hold, your score is now " + humanScore);
System.out.println("Computer, it is now your turn.");
}

Nim game - specify winner

import java.util.Scanner;
/**
*#author Andy
*#verison 21.11.2012
*/
public class NimGame
{
public static void main (String[] args)
{
System.out.println ("********** Hello Welcome to the game Nim *********");
System.out.println (" The game is relatively simple.... ");
System.out.println (" This is a game for two players. ");
System.out.println (" There is a heap containing 10 to 20 stones.");
System.out.println (" Players take turns to remove 1-4 stones ");
System.out.println (" The player who removes the last stone wins. ");
System.out.println ("******************************************************************");
Scanner scan = new Scanner (System.in);
int heapSize = 15;
int stones = 0;
boolean nextInteger = false;
boolean lessThanFour = false;
String player1 = "Player 1";
String player2 = "Player 2";
String player = player1;
System.out.println ("The number of stones currently in the heap is :- " + heapSize);
System.out.println();
while (heapSize > 0)
{
nextInteger = false;
lessThanFour = false;
System.out.println (player + ":" + "how many stones will you take from the heap?");
System.out.println();
while (nextInteger == false && lessThanFour == false)
{
if (scan.hasNextInt())
{
nextInteger = true;
stones = scan.nextInt();
if (stones <=4 && stones >0)
{
System.out.println();
System.out.println ("You picked " + stones);
heapSize = (heapSize - stones);
if (heapSize >= 0)
{
System.out.println();
System.out.println ("There are " + heapSize + "stones left");
System.out.println();
lessThanFour = true;
System.out.println();
if (player.equals(player1))
{
player = player2;
}
else
{
player = player1;
}
}
else
{
System.out.println ("Bad input, please try again");
nextInteger = false;
scan.nextLine();
}
}
else
{
System.out.println ("Bad input, please try again");
scan.nextLine();
}
}
}
}
}
}
I dunno how to implement a way to specify player 1 or player 2 being the winner once the sizeheap (number of stones left) reaches 0. Any help would be appreciated. Also when the sizeheap reaches a negative number, it will display 'bad input' but then any other number inserted after that also displays 'bad input.'
Thanks!
Basically, you just need to rewrite if (heapSize >= 0) so it displays a win message:
if (heapSize > 0) {...} else { ...win... }
Here's the critical part, fixed, streamlined a bit, and edited:
if (stones <= 4 && stones > 0) {
System.out.println ("\nYou picked " + stones);
heapSize = (heapSize - stones);
if (heapSize > 0) {
System.out.println ("\nThere are " + heapSize + " stones left\n\n");
// Could use a ternary operator here:
// player = (player.equals(player1) ? player2 : player1);
if (player.equals(player1)) {
player = player2;
}
else {
player = player1;
}
}
else {
if (player.equals(player1)) {
System.out.println("Player 1 wins!");
}
else {
System.out.println("Player 2 wins!");
}
}
}
Further tips:
You can just use a newline \n instead of an System.out.println().
The lessThanFour flag is probably unnecessary

how to set a switch statement in while loop in java

I want to do a switch in while loop where at the break of every switch statement the while loop stops and ask for an input like F, R, C, Q. The statement below works but the statement does not break. Please help
public static void main(String[] args) throws IOException {
// start both with 1 point
int goodTotal = 50;
int monTotal = 50;
// input switch statement
while (goodTotal > 0 && monTotal > 0) {
System.out.print("Type a letter: ");
System.out.println("\n");
System.out.print("F: Go out and Fight ");
System.out.println("\n");
System.out.print("R: Rest ");
System.out.println("\n");
System.out.print("C: Check Stats ");
System.out.println("\n");
System.out.print("Q: Quit ");
int input = System.in.read();
System.out.println("You typed: " + (char) input);
switch (input) {
case 'f':
System.out.println("Continue the game");
break;
case 'r':
System.out.println("Players should rest");
break;
case 'c':
System.out.println("Checking the status of the game");
System.out.print("Goodman has " + goodTotal + " points and Monster has " + monTotal + " points");
System.out.println("\n");
break;
case 'q':
System.out.println("Game over");
System.exit(input);
break;
default:
System.out.println("Invalid selection");
break;
}
// Set value of minimum and maximum damage
int minDmg = 2;
int maxDmg = 15;
// Get random number;
int damage = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue();
int damage2 = minDmg + Double.valueOf(Math.random() * (maxDmg - minDmg)).intValue();
// remove value of damage from started value to get total value remaining
goodTotal = goodTotal - damage;
monTotal = monTotal - damage2;
// print message if still in the game
if (goodTotal > 0) {
System.out.println("Goodman has " + goodTotal + " points left. Not bad, Man! ");
}
// if Goodman survives round 2 print a message of encouragement
if (goodTotal > 0 && count > 1 && count <= 2) {
System.out.print("This is encouraging. Goodman has lasted past roundhh " + count + ". ");
// print new message if Goodman passes round 3
} else if (goodTotal > 0 && count == 3) {
System.out.print("Goodman is as strong as Samson. He has lasted round " + count
+ " and still looks strong.");
System.out.print(" 10 hit points has been added to your total");
}
if (monTotal > 0) {
System.out.println("Wait, Monster has a total of " + monTotal + " points and is still in the game");
}
// exit if have less than 0 point, and print game over. Congratulate the winner
if (goodTotal < 0) {
System.out.println("Goodman you are out of the game");
System.out.println("The monster will take over the village. This is sad");
System.out.println("Game Over!");
} else if (monTotal < 0) {
System.out.println("Goodman has been victorious");
System.out.println("The monster is dead. The people live!!!!");
System.out.println("Game Over!");
}
System.out.println("This is the end of round " + count + " ");
System.out.println("\n");
count = count + 1;
}
}
Use a label on the loop:
loop: while (goodTotal > 0 && monTotal > 0) {
// ...
switch (input) {
case 'f':
// ...
break loop;
case 'r':
// ...
break loop;
// ...
}
// ...
}
You should use labelled breaks.
Although it probably is better to rewrite the code in a way that doesn't need them, as they're not very easy to read.
input is of type int, but the case labels are character literals ( i.e., f,r,c,q). Why don't you just make the input also a char type ?
char input = System.in.read();

Categories

Resources