Correcting and improving java code - java

The code I have written so far, is below and works however I am having a few issues with it
1) It runs the program more than once
2) The numbers don't seem to be very random, it seems to pick the same numbers out
3) I need the value 1 to display as Ace, the value 11 to display as Jack, the value 12 to display at Queen and the value 13 to display as King
I have gone over my code several times and cant figure out why it is doing point 1
I am not sure if it is just me, or if it is an issue with point 2
I know I need an if statment to do number 3 but not quite sure where to put it
The idea of the program is for the player to verse the computer and draw 7 cards each in turn, (suite doesn't need to be included) and output each card followed by the winner, with 1 output as ace, 11 output as jack, 12 output as queen and 13 output at king.
Many thanks for your help
import java.math.*;
import java.util.*;
public class CardProj {
public static void main(String[] args) {
Scanner mykbd = new Scanner(System.in);
Random rn = new Random();
{
for (int i = 0; i < 14; i++) {
int card1player = 0;
int card2player = 0;
int card3player = 0;
int card4player = 0;
int card5player = 0;
int card6player = 0;
int card7player = 0;
int card1Computer = 0;
int card2Computer = 0;
int card3Computer = 0;
int card4Computer = 0;
int card5Computer = 0;
int card6Computer = 0;
int card7Computer = 0;
System.out.println("Player Card 1: " + card1player);
card1Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 1: " + card1Computer);
System.out.println("");
card2player = rn.nextInt(7) + 1;
System.out.println("Player Card 2: " + card2player);
card2Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 2: " + card2Computer);
System.out.println("");
card3player = rn.nextInt(7) + 1;
System.out.println("Player Card 3: " + card3player);
card3Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 3: " + card3Computer);
System.out.println("");
card4player = rn.nextInt(7) + 1;
System.out.println("Player Card 4: " + card4player);
card4Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 4: " + card4Computer);
System.out.println("");
card5player = rn.nextInt(7) + 1;
System.out.println("Player Card 5: " + card5player);
card5Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 5: " + card5Computer);
System.out.println("");
card6player = rn.nextInt(7) + 1;
System.out.println("Player Card 6: " + card6player);
card6Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 6: " + card6Computer);
System.out.println("");
card7player = rn.nextInt(7) + 1;
System.out.println("Player Card 7: " + card7player);
card7Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 7: " + card7Computer);
System.out.println("");
int playertotal = card1player + card2player + card3player + card4player + card5player + card6player + card7player;
int computertotal = card1Computer + card2Computer + card3Computer + card4Computer + card5Computer + card6Computer + card7Computer;
if (playertotal > computertotal) {
System.out.print("Player Wins, Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
} else if (computertotal > playertotal) {
System.out.print("Computer Wins, Computer Score is, " + computertotal + " Players Score is, " + playertotal + " ");
} else {
System.out.print("Draw Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
}
}
}
}
}

You can create an array of cardPlayers and cardComputers. For instance try this below
int numPlayers = 14;
int [] cardPlayer = new int[numPlayers];
int [] cardComputer = new int[numPlayers];
for (int i = 0; i < numPlayers; i++) {
System.out.println("Player Card " + i + ": " + cardPlayer[i]);
cardComputer[i] = rn.nextInt(7) + 1;
System.out.println("Computer Card " + "i" + cardComputer[i]);
System.out.println("");
}
This will make your code more readable and reduce lines in total

Related

I am stuck, trying to make a turn based game but have been having trouble ending a turn and starting a new one

I can end the first. I am trying to make it on odd turns player goes and even turns CPU goes.
public static void main(String[] args) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
String mage = "mage";
System.out.println("mage, warrior, assassin, ranger?");
String input = keyboard.nextLine();
int playerAttackDice = random.nextInt(20) + 1;
int cpuAttackDice = random.nextInt(20) + 1;
int playerDefenseDice = random.nextInt(5) + 1;
int cpuDefenseDice = random.nextInt(5) + 1;
int turn = 1;
while(mage.equalsIgnoreCase(input)) {
Mage player = new Mage();
Warrior CPU = new Warrior();
System.out.println("You have selected: mage");
System.out.println("Your Attack Power is: " + player.getMageAttack());
System.out.println("Your Defense is: " + player.getMageDefense());
System.out.println("Your Health is: " + player.getMageHealth());
System.out.println("Your enemy is a: warrior");
System.out.println("Enemy Attack Power is: " + CPU.getMageAttack());
System.out.println("Enemy Defense is: " + CPU.getMageDefense());
System.out.println("Enemy Health is: " + CPU.getMageHealth());
System.out.println();
This is where the turn begins. I was trying to set it to make it player goes on odd numbers in the when the CPU goes. Am I even approaching this in the right way? Any help would be very much appreciated.
while(player.mageHealth != 0) {
System.out.println("Your health is: " + player.mageHealth);
for(turn = 1; turn % 1 ==0; turn++) {
if(turn % 1==0) {
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
return;
}
}
turn++;
for(turn = 2; turn % 2 ==0; turn++) {
while(turn % 2==0) {
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
}
}
}
System.out.println("end loop");
break;
}
}
If you want Player and CPU to play their move one after another - just put their actions one after another with no inner loops and complex conditions around
while (!game.isOver()) {
player.makeMove();
cpu.makeMove();
}
or having your code there
while(player.mageHealth > 0) { // game over condition
//player move
System.out.println("Your health is: " + player.mageHealth);
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
//cpu move
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
player.mageHealth = player.mageHealth + playerDefence - cpuDamage;
}

I have a question about the while loop in my code

How do I make the while loop stop forcefully by using playerHP when it becomes zero? Sometimes I would put an If statement around it, but it wouldn't work. New to coding so it would be cool to give some tips too. :)
public class RPGFight {
public static void main (String args[]) {
int playerHP = 30;
int boss1HP = 420;
int exp = 0;
System.out.println("You open the chamber door to see what lies beyond.");
System.out.println("A demogorgon jumps out and attacks!");
System.out.println("You deftly pull out your mighty blade and defend youself");
while (boss1HP > 0) {
if (boss1HP > 0) {
int hit1 = (int)(Math.random()*20);
int hit2 = (int)(Math.random()*20);
int hit3 = (int)(Math.random()*20);
int hit4 = (int)(Math.random()*20);
int hit5 = (int)(Math.random()*20);
int hit6 = (int)(Math.random()*20);
int bossDMG = (int)(Math.random()*5);
System.out.println("\nYou hit the demogorgon for " + hit1 + " points of damage");
System.out.println("You hit the demogorgon for " + hit2 + " points of damage");
System.out.println("You hit the demogorgon for " + hit3 + " points of damage");
System.out.println("You hit the demogorgon for " + hit4 + " points of damage");
System.out.println("You hit the demogorgon for " + hit5 + " points of damage");
System.out.println("You hit the demogorgon for " + hit6 + " points of damage");
System.out.println("You have been hit for " + bossDMG + " points of damage");
playerHP -= bossDMG;
boss1HP -= hit1+hit2+hit3+hit4+hit5+hit6;
}
if (boss1HP < 0) {
int expbattle = (int)(Math.random()*126+5);
exp += expbattle;
System.out.println("\nThe demogorgon falls to the floor, lifeless.");
System.out.println("Congratulations! You earned " + expbattle + " points of experience.");
}
}
}
}
Put the if condition after
playerHP -= bossDMG;
if (playerHP < 1)
break;
this will break the while loop when playerHP value is less than equal to 0.
By adding a break immediately after you modify the playerHP after checking that is less than or equal to zero. Like,
playerHP -= bossDMG;
if (playerHP <= 0) {
break;
}
// ...

PIG Dice game compiles and runs perfectly, but variables not changing from if statement. Suggestions?

package baker;
import java.util.Scanner;
import java.util.Random;
public class PIG {
final static int WINNING_SCORE = 100;
final static int COMPUTER_THRESHOLD = 20;
final static int NUM_SIDES = 6;
public static void main(String[] args) {
int turnScore = 0;
int turnScoreIf1 = 0;
int computerScore = 0;
int humanScore = 0;
int diceRoll;
boolean turnContinues = true;
String answer;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
while ((humanScore < WINNING_SCORE) && (computerScore < WINNING_SCORE)) {
System.out.println("Your turn");
while (turnContinues)
{
System.out.print("Type r to Roll, or h to Hold ");
answer = keyboard.next();
if (answer.equals("r"))
{
diceRoll = generator.nextInt(NUM_SIDES) + 1;
System.out.println("You rolled a " + diceRoll + "\n");
if (diceRoll == 1)
{
turnScore = 0;
System.out.println("Your total score is " + humanScore + ", ending turn" + "\n");
break;
}
else {
humanScore = humanScore + diceRoll;
turnScore = turnScore + diceRoll;
System.out.println("Your Turn Score: " + turnScore);
System.out.println("Your Total Score: " + humanScore +"\n");
if (humanScore >= 100)
{
System.out.println("You Win!" + "\n");
return;
}
}
}
else if (answer.equals("h")) {
System.out.println("You chose to hold");
System.out.println("Your total score is " + humanScore);
if (humanScore >= 100)
{
System.out.println("You win!");
return;
}
System.out.println("");
break;
}
}
turnScore = 0;
System.out.println("Computer's Turn" + "\n");
while (turnContinues)
if (turnScore >= COMPUTER_THRESHOLD) {
System.out.println("Computer chose to hold.");
System.out.println("Computer's total score is " + computerScore + "\n");
if (computerScore >= 100)
{
System.out.println("The computer wins!" + "\n");
return;
}
break;
}
else {
diceRoll = generator.nextInt(NUM_SIDES) + 1;
System.out.println("The computer rolled " + diceRoll);
if (diceRoll == 1)
{
System.out.println("Computer's total score is " + computerScore + ", ending turn" + "\n");
break;
}
else
{
computerScore = computerScore + diceRoll;
turnScore = turnScore + diceRoll;
System.out.println("Computer turn score: " + turnScore);
System.out.println("Computer total score: " + computerScore +"\n");
if (computerScore >= 100) {
System.out.println("The Computer Wins!" + "\n");
return;
}
}
}
turnScore = 0;
}
}
}
Like I said, the code runs fine, up until the code must reset for diceRoll == 1;. for whatever reason, the variable just doesn't change. As a matter of fact, the line forces the "assigned variable is never used. Any help is appreciated...
Not entirely clear on the issue, but I added a method to reset the scores, calling it whenever there's a win condition. Is this what you mean by "the variable doesn't change"?
package baker;
import java.util.Scanner;
import java.util.Random;
public class PIG {
final static int WINNING_SCORE = 100;
final static int COMPUTER_THRESHOLD = 20;
final static int NUM_SIDES = 6;
//moved these out of main so we can use a method to reset
static int turnScore = 0;
static int computerScore = 0;
static int humanScore = 0;
public static void main(String[] args) {
int diceRoll;
boolean turnContinues = true;
String answer;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
while ((humanScore < WINNING_SCORE) && (computerScore < WINNING_SCORE)) {
System.out.println("Your turn");
while (turnContinues)
{
System.out.print("Type r to Roll, or h to Hold ");
answer = keyboard.next();
if (answer.equals("r"))
{
diceRoll = generator.nextInt(NUM_SIDES) + 1;
System.out.println("You rolled a " + diceRoll + "\n");
if (diceRoll == 1)
{
turnScore = 0;
System.out.println("Your total score is " + humanScore + ", ending turn" + "\n");
break;
}
else {
humanScore = humanScore + diceRoll;
turnScore = turnScore + diceRoll;
System.out.println("Your Turn Score: " + turnScore);
System.out.println("Your Total Score: " + humanScore +"\n");
if (humanScore >= 100)
{
System.out.println("You Win!" + "\n");
resetScores();
return;
}
}
}
else if (answer.equals("h")) {
System.out.println("You chose to hold");
System.out.println("Your total score is " + humanScore);
if (humanScore >= 100)
{
System.out.println("You win!");
resetScores();
return;
}
System.out.println("");
break;
}
}
turnScore = 0;
System.out.println("Computer's Turn" + "\n");
while (turnContinues)
if (turnScore >= COMPUTER_THRESHOLD) {
System.out.println("Computer chose to hold.");
System.out.println("Computer's total score is " + computerScore + "\n");
if (computerScore >= 100)
{
System.out.println("The computer wins!" + "\n");
resetScores();
return;
}
break;
}
else {
diceRoll = generator.nextInt(NUM_SIDES) + 1;
System.out.println("The computer rolled " + diceRoll);
if (diceRoll == 1)
{
System.out.println("Computer's total score is " + computerScore + ", ending turn" + "\n");
break;
}
else
{
computerScore = computerScore + diceRoll;
turnScore = turnScore + diceRoll;
System.out.println("Computer turn score: " + turnScore);
System.out.println("Computer total score: " + computerScore +"\n");
if (computerScore >= 100) {
System.out.println("The Computer Wins!" + "\n");
resetScores();
return;
}
}
}
turnScore = 0;
}
}
public static void resetScores() {
turnScore = 0;
computerScore = 0;
humanScore = 0;
}
}

Can't figure out how to reset an int so I can use my loop properly making the game of Pig

When it is the computer's turn I need it to keep going until it reaches 35 points for the current turn but I am not sure how to reset it back to 0 for a new turn so every time after the computer reaches 35 points it will only go once.
import java.util.Scanner;
import java.util.Random;
public class PigGamev1
{
public static void main(String[] args)
{
int humanScore = 0;
int computerScore = 0;
int win = 100;
int die1 = 0;
int die2 = 0;
int total = 0;
boolean gameOver = false;
boolean turnOver = false;
char repeat = 'r';
String input;
Scanner keyboard = new Scanner(System.in);
Random randomGenerator = new Random();
do
{
//human rolls dice
do
{
die1 = randomGenerator.nextInt(6) + 1;
die2 = randomGenerator.nextInt(6) + 1;
total = die1 + die2;
if(total == 2)
{
humanScore += 0;
System.out.println("You rolled a: " + total);
System.out.println("Turn over.");
System.out.println("Your current score is " + humanScore);
turnOver = true;
}
else if(humanScore <= win && total != 2)
{
humanScore += total;
System.out.println("You rolled a: " + total);
if(humanScore >= win)
{
System.out.println("Your score is " + humanScore + " and my score is "
+ computerScore);
System.out.println("You win!");
turnOver = true;
gameOver = true;
System.exit(0);
}
System.out.println("Your current score is " + humanScore);
System.out.println("Enter r to roll again or h to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'r')
{
turnOver=false;
}
else if(repeat == 'h')
{
System.out.println("Turn over.");
System.out.println("Your current score is " + humanScore +
" total computer score is " + computerScore + "\n");
turnOver = true;
}
}
}while(turnOver == false);
//computer rolls dice
System.out.println("My turn! \n");
do
{
turnOver = false;
die1 = randomGenerator.nextInt(6) + 1;
die2 = randomGenerator.nextInt(6) + 1;
total = die1 + die2;
System.out.println("I rolled a: " + total);
if(total == 2)
{
computerScore += 0;
System.out.println("Turn over.");
System.out.println("My current score is " + computerScore + "\n");
turnOver = true;
}
else
{
computerScore += total;
System.out.println("My current score is " + computerScore + "\n");
if(computerScore >= 35)
{
System.out.println("I hold.");
System.out.println("Your turn!\n");
System.out.println("My current score is " + computerScore +
" your score is " + humanScore + "\n");
turnOver = true;
}
}
if(computerScore >= win)
{
System.out.println("I win!");
turnOver = true;
gameOver = true;
System.exit(0);
}
}while(turnOver == false);
}while(gameOver == false);
keyboard.close();
}
}
Use different variables to keep track of the total score for the computer and the score it has on their current turn. For instance, you could define int computerTurn; with the rest of your variables, and use it as such in your program, remembering to reset it to 0 when the turn ends:
//some code omitted if not relevant to your problem
do
{
if(total == 2)
{
computerScore += computerTurn; //adds current turn to running total
System.out.println("Turn over.");
System.out.println("My current score is " + computerScore + "\n");
turnOver = true;
}
else
{
computerTurn+= total;
System.out.println("My current score is " + computerScore + "\n");
if(computerTurn >= 35) //checks against current turn instead of total
{
computerScore += computerTurn; //adds current turn to running total
System.out.println("I hold.");
System.out.println("Your turn!\n");
System.out.println("My current score is " + computerScore +
" your score is " + humanScore + "\n");
turnOver = true;
}
}
}while(turnOver == false);
computerTurn = 0;

Sports game summary using Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
IndexOutOfBounds with array
(5 answers)
Closed 6 years ago.
The basic idea of this assignment is to create a program that can provide a summary and identify who won a "match" in a sports event (football, basketball, Soccer, baseball, etc.)
**This is my code:**
`import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
int numberOfScoresT1[] = new int[sc.nextInt()];
System.out.println("How many " + scoreName + " for " + t2N + "?");
int numberOfScoresT2[] = new int[sc.nextInt()];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}`
This is the error I'm receiving:
Please enter game name:
Football
Please enter Football team 1 name:
Dolphins
Please enter Football team 2 name:
Jaguars
What is a score in Fotball called?
Touchdown
How many points per Touchdown in Fotball?
7
What is a period in Fotball called?
Quarter
How many Quarter in Fotball?
4
Quarter #1
How many Touchdown for Dolphins?
3
How many Touchdown for Jaguars?
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Team.main(Team.java:36)
I recognize that the arrays I'm using are in the for loop, and I think thats what is causing the problem, but i'm not sure how to fix it.
This is a sample output is supposed to look like:
Quarter #1:
How many Touchdowns for Dolphins? 2
How many Touchdowns for Chargers? 1
Quarter #2:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 1
Quarter #3:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 2
Quarter #4:
How many Touchdowns for Dolphins? 3
How many Touchdowns for Chargers? 0
Football Game Results:
Dolphins scored 5 Touchdowns for a score of 35
Chargers scored 4 Touchdowns for a score of 28
Dolphins Win by 7 points!
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
Should the second parameter of the loop be
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
seeing as you are accessing numberOfScoresT2 array in the body.
Your inner for loops should be as follows
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
sum2 += numberOfScoresT2[counter];
You have used length of array numberOfScoresT1 instead of array numberOfScoresT2 in second inner for loops.
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int numberOfScoresT1[] = new int[numberOfPeriods];
int numberOfScoresT2[] = new int[numberOfPeriods];
for (int i = 0; i <numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
numberOfScoresT1[i] = sc.nextInt();
System.out.println("How many " + scoreName + " for " + t2N + "?");
numberOfScoresT2[i] = sc.nextInt();
}
sc.close();
for (int counter = 0; counter < numberOfPeriods; counter++) {
sum1 += numberOfScoresT1[counter];
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}
}

Categories

Resources