I'm completely new to coding and I was wondering if you guys can help me. This is part of a code in which you battle a vampire, RPG style. My program does not loop back to my characters turn after I set the turn number to one near the bottom of the code, why is this?
/**
* Created by f on 7/30/2014.
*/
import java.util.Scanner;
import java.util.Random;
public class rpgBattle {
public static void main(String[] args) {
// Declarations
int charHp = 3941;
int enemyHp = 5200;
String charName;
int numDmg;
int dmgMultiplier = 1;
String playerInputSt;
int playerInput;
int turn = 1;
int miss;
//Processes
Scanner user_input = new Scanner(System.in);
System.out.println("Enter your name.");
charName = user_input.next();
System.out.println();
System.out.println("A vampire emerged!");
do {
System.out.println();
System.out.println(charName + "'s HP: " + charHp + "/3941");
System.out.println("The Vampire's HP: " + enemyHp + "/5200");
System.out.println("What will you do?");
System.out.println("Enter the number corresponding to the action you would like to perform.");
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println(turn);
playerInputSt = user_input.next();
playerInput = Integer.parseInt(playerInputSt);
if (playerInput == 1) {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println("The Vampire protected itself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(100) + 550;
}
enemyHp = enemyHp - numDmg / 1;
System.out.println();
System.out.println(charName + " attacks!");
System.out.println("The Vampire took " + numDmg / dmgMultiplier + " damage!");
turn = 2;
} else if (playerInput == 2) {
System.out.println();
System.out.println(charName + " guards");
System.out.println(charName + " recovered 394 HP!");
charHp = charHp + 394;
dmgMultiplier = 2;
turn = 2;
};
} while (charHp > 0 && enemyHp > 0 && turn !=2);
do {
Random rand = new Random();
miss = rand.nextInt(19);
if (miss == 0) {
System.out.println();
System.out.println(charName + " braced himself.");
numDmg = 0;
} else {
numDmg = rand.nextInt(500) + 200;
charHp = charHp - numDmg / dmgMultiplier;
}
System.out.println("The Vampire attacks!");
System.out.println(charName + " took " + numDmg / dmgMultiplier + " damage!");
dmgMultiplier = 1;
turn = 1;
} while (turn == 2);
}
}
It will never end because in the top level loop, the condition to get out is that the character's health drops below 0. However, you are never decreasing his HP. You are only decreasing the vampire's HP, but not the character. If you want the game to end, make the vampire attack the character too. That way, in some point his HP will drop below 0 and the game will end.
However, to make it more realistic, you should make the game end when the HP of the vampire OR the character are 0, and not when both of them are below 0. To achieve that, instead of using 3 loops, use 2, but changing the condition so that when either one of them has no HP, it will end:
do {
do {
...
} while (turn == 1);
} while (charHp > 0 && enemyHp > 0);
Without spending too much time analyzing all of your code, it looks like you have nested a Do..While Loop for charHp and a Do..While Loop for enemyHp. I think you need only one Do..While Loop that loops until either charHp or enemyHp is zero.
do {
do {
//.... Lots of code removed for brevity in the answer .....
} while (turn == 1);
} while ((enemyHp > 0) && (charHp > 0));
or should it be like this, with only one Do..While Loop
do {
//.... Lots of code removed for brevity in the answer .....
} while ((turn == 1) && (enemyHp > 0) && (charHp > 0));
What is the purpose of the variable turn ? Once a valid value is entered its value will be 2 untill the end of the game so the inner while will always loop only once.
But the the code will still be executed each time as the outer loops continue to loop until a score drops to 0.
If you want to know the number of turns you are playing, you should increase turn:
turn++;
and remove the most inner while loop.
If you want to loop until the user has entered a valid value, you should initialise turn at the beginning of the most inner loop:
turn=1;
good luck.
Related
I am coding a pig game in Java, and I need help adding up the score. The game's goal is to roll two dice, and the values of those two dice are added together, and the player who gets to 100 first wins. I want to loop the values (which I called "Added") so that it continuously adds up by themselves.
Thank you in advance
By the way, I'm hardly done most of the game, so mind the gaps, lol.
import java.util.Random;
import java.util.Scanner;
public class Pig {
static int player, Continue, roll1, roll2;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
Random r2 = new Random();
System.out.print("Enter 1 to play against computer\nEnter 2 to play against another person\n");
player = keyboard.nextInt();
if (player == 1) {
System.out.println("\nPlaying against the computer...");
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added = roll1 + roll2;
System.out.println("\nYour total is " + added);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
if (Continue == 1) {
do {
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added2 = roll1 + roll2;
int added3 = added + added2;
added = added2;
added2 = added3;
System.out.println("\nYour total is " + added3);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
} while (Continue == 1);
}
} else {
System.out.print("Bye");
}
/*if (player == 2){
System.out.println("Playing against another person...");
}
else {
System.out.print("Bye");
count++;
*/
}
}
So i'm making a blackjack program. I've successfully made the game almost fully except one bug type thing. The user gets the option to 'hit' or 'stay' as you usually would in blackjack but when it tells them their total in the end it will add the 2 'hits' even if they said stay twice. For example if I got a 4 and a 6 for a total of 10. Then I just stay twice to keep the 10. The program rolls 2 more numbers anyway and at the end will say the total of like 20 instead of the 10 I initially got. You can run my program to see more if you want so here is the code;
/////////////////////////////////////
// Name: Mackenzie Cutler
// Class: CP 12
// Date: March 28th, 2018
/////////////////////////////////////
import java.util.Scanner;
import java.util.Random;
public class MCproject3
{
public static void main(String[] args)
{
Scanner k = new Scanner(System.in);
Random ran = new Random();
//Welcoming user & choosing their initial cards
System.out.println("Welcome to the Cutler Casino Program. Currently playing Blackjack!");
int a1 = ran.nextInt(11) + 1;
int a2 = ran.nextInt(10) + 1;
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;
System.out.println ("\nYou get a " + a1 + " and a " + a2);
System.out.println ("Your total is " + (a1+a2));
//Choosing dealers initial cards and telling user
int b1 = ran.nextInt(11) + 1;
int b2 = ran.nextInt(10) + 1;
int b3 = ran.nextInt(11) + 1;
int b4 = ran.nextInt(11) + 1;
System.out.println("\nThe dealer has a " + b1 + " showing, and a hidden card.");
System.out.println("His total is hidden, too.");
//User chooses to 'Hit' or 'Stay'
System.out.print("\nWould you like to 'Hit' or 'Stay'?");
String choice = k.nextLine();
if(choice.equalsIgnoreCase ("hit"))
{
System.out.println("You drew a " + a3);
System.out.println("Your total is " + (a1+a2+a3));
if(a1+a2+a3 > 21)
{
System.out.println("You busted! Since you exceeded 21 the dealer wins, sorry.");
return;
}
}
else if(choice.equalsIgnoreCase ("stay"))
{
System.out.println(" ");
}
else
{
System.out.println("Error. Make sure you typed either 'Stay' or 'Hit'. Please re-run the program :)");
}
//Second time user chooses to 'Hit' or 'Stay'
System.out.print("\nWould you like to 'Hit' or 'Stay'?");
String choice2 = k.nextLine();
if(choice2.equalsIgnoreCase ("hit"))
{
System.out.println("You drew a " + a4);
System.out.println("Your total is " + (a1+a2+a3+a4));
if(a1+a2+a3+a4 > 21)
{
System.out.println("You busted! Since you exceeded 21 the dealer wins, sorry.");
return;
}
}
else if(choice2.equalsIgnoreCase ("stay"))
{
System.out.println(" ");
}
else
{
System.out.println("Error. Make sure you typed either 'Stay' or 'Hit'. Please re-run the program :)");
}
//Dealers reveal and is his turn to choose 'Hit' and 'Stay'
System.out.println("\nOkay, Dealers turn.");
System.out.println("His hidden card was " + b2);
System.out.println("His total was " + (b1+b2));
int dchoice = ran.nextInt(2) + 1;
if(dchoice == 1)
{
System.out.println("\nDealder chooses to hit.");
System.out.println("He draws a " + b3);
System.out.println("His total is now " + (b1+b2+b3));
if(b1+b2+b3 > 21)
{
System.out.println("Dealer busted! Since he exceeded 21 you WIN!!");
return;
}
}
else if(dchoice == 2)
{
System.out.println("\nDealer chooses to stay.");
}
else
{
System.out.println("Error 404. Program Failed, We are sorry. Please restart.");
}
//Dealers second 'Hit' or 'Stay' random choice
int dchoice2 = ran.nextInt(2) + 1;
if(dchoice2 == 1)
{
System.out.println("\nDealder chooses to hit.");
System.out.println("He draws a " + b4);
System.out.println("His total is now " + (b1+b2+b3+b4));
if(b1+b2+b3+b4 > 21)
{
System.out.println("Dealer busted! Since he exceeded 21 you WIN!!");
return;
}
}
else if(dchoice == 2)
{
System.out.println("\nDealer chooses to stay.");
}
else
{
System.out.println(" ");
}
//Ending
int totala = (a1+a2+a3+a4);
int totalb = (b1+b2+b3+b4);
System.out.println("\nDealers total is " + (b1+b2+b3+b4));
System.out.println("Your total is " + (a1+a2+a3+a4));
if(totala > totalb)
{
if(totala <= 21)
{
System.out.println("\nYou WIN!");
}
else if(totala > 21)
{
System.out.println("\nYou busted so you wont win :(");
}
}
else if(totala < totalb)
{
if(totalb <= 21)
{
System.out.println("\nSorry, Dealer Wins.");
}
else if(totalb > 21)
{
System.out.println("Dealer busted so you win!");
}
}
else
{
System.out.println("\nError 405. Program Failed, We are sorry. Please restart.");
}
}
}
I just want to know if you think there is anything I did wrong or should do differently to make it work correctly.
The problem is very simple yet elusive.
You have displayed a1+a2 for the first total. However, while displaying the results, you show a1+a2+a3+a4. Now, a3 and a4 are already initialized to some random numbers, therefore the final result will always be more than the initial, even if you 'stay' twice.
Solution -
To fix this, you can create a variable called int UserTotal = a1+a2, and add a3 to it if the user 'hits' the first time, and a4 to it if the user 'hits' the second time. Then, initialize totala to UserInput.
Or, you can set a3 and a4 to 0 at the very start of the program, and if the user 'hits' the first time, you can set a3 to a random value, and if user hits the second time, a4 can be set to a random value.
You are always calculating the totals like this:
int totala = (a1+a2+a3+a4);
int totalb = (b1+b2+b3+b4);
These variables a1, a2, etc. are assigned values at the very start of your main method like so:
int a1 = ran.nextInt(11) + 1;
int a2 = ran.nextInt(10) + 1; // is this correct?
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;
So regardless of what the user inputs, it will always calculate the sum of the 4 values as the total.
To resolve this, give a3 and a4 initial values of 0, and only assign values if they "hit".
One alternative is to store the numbers in a List, that way the sum is just the total of the integers in the List, e.g.
List<Integer> playerCards = new ArrayList<>();
// Add initial cards...
playerCards.add(ran.nextInt(11) + 1);
playerCards.add(ran.nextInt(11) + 1);
if (playerHit) { // for example...
playerCards.add(ran.nextInt(11) + 1);
}
// Calculate player total
int playerTotal = 0;
for (int cardValue : playerCards) {
playerTotal += cardValue;
}
System.out.println("Player total is: " + playerTotal);
Additionally your code has a lot of repetition, you should consider refactoring it into smaller reusable methods.
You just need to set these two variables below when they actually do decide to hit and not automatically at the start. Otherwise you want these two variables to be zero at the start, so that way when they don't hit you add everything you get the correct result!
int a3 = ran.nextInt(11) + 1;
int a4 = ran.nextInt(11) + 1;
I am working in java and I want my loop to run for as long as there are projects as specified by the user. As of now, the code runs through for one iteration, and reads the results of the one loop, but it won't continue any further.
If the user says there are 3 projects, I want the code to run through the loop 3 times and tell me the total of each project. Right now, it tells me the total of 1 project whether I specify the number of projects are 1 or 5.
double projectBoardFootage = 1.0;
double projectBoardFootageTotal = 0.0;
int i = 0;
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(i = 0; i < numberOfProjects; ++i) {
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}
Perhaps you want to reinitialize the total board footage to clear the previous iteration count?
for(i = 0; i < numberOfProjects; ++i) {
projectBoardFootageTotal = 0.0;
while (projectBoardFootage > 0) {
System.out.println("Enter your board footage for Project #" + (i + 1) + " (0 to exit)");
projectBoardFootage = scan.nextDouble();
projectBoardFootageTotal += projectBoardFootage;
}
System.out.println("The raw board footage for Project #" + (i + 1) + " is: " + projectBoardFootageTotal);
}
The problem in your code is that you're using the variable projectBoardFootage to terminate the loop.
Think about what happens when this value is set to 0.
We exit the while-loop, and the value never gets changed again. So from that point on, every iteration will end immediately.
The better solution is to do something like this:
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How many projects do you want to estimate?");
int numberOfProjects = scan.nextInt();
for(int i = 0; i < numberOfProjects; ++i) {
foobar(scan, i+1);
}
}
private static void foobar(Scanner scan, int projectNr)
{
boolean wantsToQuit = false;
double projectBoardFootageTotal = 0;
while (!wantsToQuit) {
System.out.println("Enter your board footage for Project #" + projectNr + " (q to exit)");
String tmp = scan.next();
if(tmp.equalsIgnoreCase("q"))
wantsToQuit = true;
else
projectBoardFootageTotal += Double.parseDouble(tmp);
}
System.out.println("The raw board footage for Project #" + projectNr + " is: " + projectBoardFootageTotal);
}
This code also ensures the user enters a more sensible keycode than '0' to quit.
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
So i'm still a beginner but I managed to get this code but it didn't work like I wanted, my main problem is that every time I press 1 it resets the enemy instead of keeping the same one. I would really appreciate if someone could help me. So far I have only made writing 1 do something.
package Game;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random r = new Random();
System.out.println("Welcome to Dragon Heart");
System.out.println("1. Start");
System.out.println("2. Quit");
int input = 0, enemyhealth = 75, enemyattack = 15, playerhealth = 100, playerattack, random;
boolean enemydead = true, playerdead = false;
input = in.nextInt();
if (input == 1) {
System.out.println("Game started!");
while (0 != 1) {
if (enemydead = true) {
enemyhealth = r.nextInt(50) + 51;
enemyattack = r.nextInt(15) + 6;
System.out.println("An enemy appears, it has " + enemyhealth + " health points and " + enemyattack + " attack points");
} else {
System.out.println("The enemy now has " + enemyhealth + "health points");
}
System.out.println("1. Attack");
System.out.println("2. Defend");
System.out.println("3. Run away");
System.out.println("4. Do nothing");
input = in.nextInt();
if (input == 1) {
playerattack = r.nextInt(5) + 21;
random = r.nextInt(2) + 1;
enemyhealth = enemyhealth - playerattack;
if (random == 1) {
playerhealth = playerhealth - enemyattack;
}
if (enemyhealth <= 0) {
enemydead = true;
System.out.println("The enemy has been killed");
} else {
enemydead = false;
}
}
}
} else if (input == 2) {
System.out.println("Game quit.");
}
}
}
Your logic for defense away is dubious, but your problem is here:
if(enemydead = true)
You're reassigning enemydead to true every single time.
You really want to check if the enemy is dead, which is accomplished with this:
if(enemydead)
Further, you could clean up while (0 != 1) to be while(true) instead. However, you're going to need to include a break statement somewhere in that loop so that it's not an infinite loop like it is now.
Lastly, it's a good idea to have lower-case package names as opposed to upper-case package names.