Choosing random Index from Array of Objects - Java - java

I am trying to code a text based Adventure Game, but the random enemy selection does not work. Always the "Assassin" gets chosen, but I can't figure out why.
package defaultdfs;
import java.util.Random;
import java.util.Scanner;
public class main {
// System Objects
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
//OBJ
static Entity s = new Entity("Skeleton", 200, 5, 2, 200);
static Entity z = new Entity("Zombie", 150, 2, 1, 150);
static Entity w = new Entity("Warrior", 175, 3, 1, 175);
static Entity a = new Entity("Assasin", 75, 1, 1, 75);
// Game Variables
static Entity[] enemies = {w, z, s, a};
static int maxEnemyHealth = 75;
static int enemyAttackDam = 25;
// Player Variables
static int health = 100;
static int attackDamage = 50;
static int numHealthPot = 3;
static int healthPotHealAmount = 30;
static int healthPotDropChance = 50;
static int ShieldDropChance = 0;
static int enemyCounter = 0;
static int defense = 0;
static int enemyHealth = 0;
static int damageDealt = 0;
static int damageTaken = 0;
//Items
static boolean sword = false;
static int swordDropChance = 0;
static boolean running = true;
static Entity enemy;
public static void main(String[] args) {
welcome();
GAME: while (running) {
System.out.println("-------------------------------------------------");
int ra = rand.nextInt(enemies.length); //RANDOM ENEMY SELECTION in two steps
enemy = enemies[ra];
// enemy = enemies[rand.nextInt(enemies.length)]; //in one step
System.out.println(ra);
System.out.println("\t# " + enemy.name + " appeared! #\n");
while (enemy.enemyHealth > 0) {
monitoring(enemy, Entity.enemyHealth);
String input = in.nextLine();
if (input.equals("1")) {
damageDealt = rand.nextInt(attackDamage);
damageTaken = rand.nextInt(enemyAttackDam);
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
System.out.println("\t> You strike the " + enemy.name + " for " + damageDealt + " damage.");
System.out.println("\t> You recive " + damageTaken + " in retaliation!");
if (health < 1) {
dead();
break;
}
} else if (input.equals("2")) {
healingProcess(enemy);
}
else if (input.equals("3")) {
runOption(enemy);
continue GAME;
}
else {
System.out.println("\tInvalid command!");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
defmsg(enemy);
enemyC();
healpot(enemy);
defense(enemy);
sword(enemy);
options();
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.println("Invalid command!");
input = in.nextLine();
}
if (input.equals(input.equals("1"))) {
System.out.println("You continue on ypur adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventure!");
break;
}
}
thx();
}
private static void sword(Entity enemy) {
if (rand.nextInt(100) < swordDropChance) {
attackDamage += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You attack now with +5! # ");
}
}
private static void defmsg(Entity enemy) {
System.out.println("-------------------------------------------------");
System.out.println(" # " + enemy.name + " was defeated! # ");
System.out.println(" # You have " + health + "HP left. # ");
enemy.enemyHealth = enemy.inHealth;
}
private static void options() {
System.out.println("-------------------------------------------------");
System.out.println("What would you like to do now? ");
System.out.println("1. Continue fighting");
System.out.println("2. Exit dungeon");
}
private static void thx() {
System.out.println("#######################");
System.out.println("# THANKS FOR PLAYING! #");
System.out.println("#######################");
}
private static void welcome() {
System.out.println("Welcome to the Dungeon!");
}
private static void attack(int enemyHealth, int damageDealt, int damageTaken) {
enemy.enemyHealth -= damageDealt;
health -= damageTaken;
// Iteminfluence
health += defense;
}
private static void dead() {
System.out.println("\t> You have taken too much damage, you are too weak to go on!");
}
private static void monitoring(Entity enemy, int enemyHealth) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy.name + "'s HP: " + enemy.enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
}
private static void runOption(Entity enemy) {
System.out.println("\tYou run away from the " + enemy.name + "!");
}
private static void healingProcess(Entity enemy) {
if (numHealthPot > 0) {
int prevHealth = health;
health += healthPotHealAmount;
if (health == 100) {
System.out.println("You can not heal yourself!");
} else if (health > 100) {
health = 100;
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
} else {
numHealthPot--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotHealAmount + " . "
+ "\n\t> You now have " + health + " HP." + "\n\t> You have " + numHealthPot
+ " health potions left.\n");
}
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies for a chance to get one!");
}
}
private static void enemyC() {
enemyCounter++;
if (enemyCounter == 1) {
System.out.println(" # You killed one enemy! # ");
} else {
System.out.println(" # You killed " + enemyCounter + " enemies! # ");
}
}
private static void healpot(Entity enemy) {
if (rand.nextInt(100) < healthPotDropChance) {
numHealthPot++;
System.out.println(" # The " + enemy.name + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPot + " heaalth potion(s). # ");
}
}
public static void defense(Entity enemy) {
if (rand.nextInt(100) < ShieldDropChance) {
defense += 5;
System.out.println(" # The " + enemy.name + " dropped a piece of armor! # ");
System.out.println(" # You now have " + defense + " defensepoints! # ");
}
}
}
I Tried to split the part up and print out the number it choose. And the random selection works but its always the same enemy which gets chosen.
public class Entity {
static String name;
static int enemyHealth = 100;
static int ShieldDropChance = 0;
static int swordDropChance = 0;
static int inHealth = 0;
public static int getSwordDropChance() {
return swordDropChance;
}
public static void setSwordDropChance(int swordDropChance) {
Entity.swordDropChance = swordDropChance;
}
public static int getShieldDropChance() {
return ShieldDropChance;
}
public static void setShieldDropChance(int shieldDropChance) {
ShieldDropChance = shieldDropChance;
}
public static String getName() {
return name;
}
public static void setName(String name) {
Entity.name = name;
}
public static int getEnemyHealth() {
return enemyHealth;
}
public static void setEnemyHealth(int enemyHealth) {
Entity.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}

What Anon said. Change your entity class to this, and you shouldn't even need to touch the rest of your code.
Remember that static means it's one value associated with the class itself and not any particular instance. But for some reason, Java lets you reference static values via an instance (like you did), which does nothing except trick you into thinking it's not static. I really don't know why that's a thing.
public class Entity {
String name;
int enemyHealth = 100;
int shieldDropChance = 0;
int swordDropChance = 0;
int inHealth = 0;
public int getSwordDropChance() {
return swordDropChance;
}
public void setSwordDropChance(int swordDropChance) {
this.swordDropChance = swordDropChance;
}
public int getShieldDropChance() {
return shieldDropChance;
}
public void setShieldDropChance(int shieldDropChance) {
this.shieldDropChance = shieldDropChance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnemyHealth() {
return enemyHealth;
}
public void setEnemyHealth(int enemyHealth) {
this.enemyHealth = enemyHealth;
}
public Entity (String name, int enemyHealth, int ShieldDropChance, int swordDropChance, int inHealth) {
this.name = name;
this.enemyHealth = enemyHealth;
this.ShieldDropChance = ShieldDropChance;
this.swordDropChance = swordDropChance;
this.inHealth = inHealth;
}
}

Related

How can I improve my sundae program, using equals ignore case?

The program works but you need to type in Upper case or Lower case depending on the word. As well, when you choose 2 or more standard/deluxe toppings, it displays only the last input of each one. Definitely waiting for help :D. Thank you!
public class Sundae {
private final double SALES_TAX = .08625;
private final double DELUXE_TOPPING = 1.25;
private String iceCreamFlavor;
private int numberOfScoops;
private double costForScoops;
private String standardToppingList;
private String freeSyrupChoice;
private String deluxeToppingList;
private double costOfDeluxeToppings;
private int counterD;
private double costOfSundae;
private double tax;
private double total;
public Sundae()
{
}
public String getIceCreamFlavor()
{
return iceCreamFlavor;
}
public int getNumberOfScoops()
{
return numberOfScoops;
}
public double getCostForScoops()
{
return costForScoops;
}
public String getStandardToppingList()
{
return standardToppingList;
}
public String getFreeSyrupChoice()
{
return freeSyrupChoice;
}
public String getDeluxeToppingList()
{
return deluxeToppingList;
}
public double getCostOfDeluxeToppings()
{
return costOfDeluxeToppings;
}
public int getCounterD()
{
return counterD;
}
public double getCostOfSundae()
{
return costOfSundae;
}
public void setIceCreamFlavor(String choice)
{
iceCreamFlavor = choice;
}
public void setNumberOfScoops(int numberScoops)
{
numberOfScoops = numberScoops;
}
public void setCostForScoops()
{
costForScoops = numberOfScoops + 1.79;
}
public void setCounterD(int numberD)
{
counterD = numberD;
}
public void setStandardToppingList(String standardTopping)
{
standardToppingList = standardTopping;
}
public void setFreeSyrupChoice(String syrup)
{
freeSyrupChoice = syrup;
}
public void setDeluxeToppingList(String deluxeTopping)
{
deluxeToppingList = deluxeTopping;
}
public void setDefault()
{
iceCreamFlavor = "Vanilla";
numberOfScoops = 2;
costForScoops = 1.79;
standardToppingList = "Whipped Cream, Hot Fudge, Multi-Colored Sprinkles, and a cherry.";
}
public void Print()
{
costForScoops = numberOfScoops * 1.79;
costOfDeluxeToppings = DELUXE_TOPPING * counterD;
costOfSundae = costForScoops + costOfDeluxeToppings;
tax = SALES_TAX * costOfSundae;
total = costOfSundae + tax;
System.out.println("Flavor: " + iceCreamFlavor + "\nNumber of scoops: " + numberOfScoops + "\nCost for scoops: " + costForScoops
+ "\nStandard toppings: " + standardToppingList + "\nSyrup:" + freeSyrupChoice + "\nDeluxe toppings: " + deluxeToppingList
+ "\nCost of deluxe toppings: " + costOfDeluxeToppings);
System.out.printf("Subtotal: $%.2f \nSale Tax: $%.2f \nTotal: $%.2f", costOfSundae, tax, total);
}
}
Driver Program
import java.util.Scanner;
public class SundaeDriver {
public static void main(String[]args) {
Sundae sundae = new Sundae();
int numberS;
int numberD;
Scanner input = new Scanner(System.in);
System.out.println("Which sundae flavor do you want? ");
sundae.setIceCreamFlavor(input.nextLine());
if ((sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("French Vanilla"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Peanut Butter"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Chocolate Chip Cookie"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Cookie Dough"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Ice Cream Cake"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("American Dream"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Vanilla Chocolate Swirl"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Strawberry"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Mint Chocolate Chip"))||
(sundae.getIceCreamFlavor().equalsIgnoreCase("Oreo Cookies and Cream")))
{
}
else
{
sundae.setIceCreamFlavor("Vanilla");
}
System.out.println("How many scoops do you want?");
sundae.setNumberOfScoops(input.nextInt());
if ((sundae.getNumberOfScoops() == 1)||
(sundae.getNumberOfScoops() == 2)||
(sundae.getNumberOfScoops() == 3)||
(sundae.getNumberOfScoops() == 4)||
(sundae.getNumberOfScoops() == 5)||
(sundae.getNumberOfScoops() == 6))
{
}
else
{
sundae.setNumberOfScoops(2);
}
System.out.println("How many free toppings do you want?(free)");
numberS = input.nextInt();
input.nextLine();
for (int i = 0; i < numberS;i++)
{
System.out.println((i + 1) + " free toppings do you want?");
sundae.setStandardToppingList(input.nextLine());
if ((sundae.getStandardToppingList().equals("Whipped cream"))||
(sundae.getStandardToppingList().equals("Syrup"))||
(sundae.getStandardToppingList().equals("Multi colored sprinkles"))||
(sundae.getStandardToppingList().equals("Cherry")))
{
sundae.getStandardToppingList();
}
else
{
sundae.setStandardToppingList("Whipped cream, hot fudge, multi colored sprinkles and cherry");
}
}
System.out.println("Which syrup do you want?");
sundae.setFreeSyrupChoice(input.nextLine());
if ((sundae.getFreeSyrupChoice().equals("Hot fudge"))||
(sundae.getFreeSyrupChoice().equals("Chocolate"))||
(sundae.getFreeSyrupChoice().equals("Caramel")))
{
}
else
{
sundae.setFreeSyrupChoice("");
}
System.out.println("How many deluxe toppings do you want?");
numberD = input.nextInt();
sundae.setCounterD(numberD);
sundae.getCounterD();
input.nextLine();
for(int j = 0; j < numberD; j++)
{
System.out.println((j + 1) + " deluxe toppings do you want?");
sundae.setDeluxeToppingList(input.nextLine());
if((sundae.getDeluxeToppingList().equals("M&Ms"))||
(sundae.getDeluxeToppingList().equals("Crushed oreos"))||
(sundae.getDeluxeToppingList().equals("Reeses")||
(sundae.getDeluxeToppingList().equals("Chocolate chips"))||
(sundae.getDeluxeToppingList().equals("KitKats"))||
(sundae.getDeluxeToppingList().equals("Gummy Bears"))||
(sundae.getDeluxeToppingList().equals("Cookie Dough Bits"))||
(sundae.getDeluxeToppingList().equals("Marshmallows"))||
(sundae.getDeluxeToppingList().equals("Peanuts"))||
(sundae.getDeluxeToppingList().equals("Walnuts"))))
{
sundae.getDeluxeToppingList();
}
else
{
sundae.setDeluxeToppingList("");
}
}
sundae.Print();
input.close();
}
}
This looks like a perfect time to use enum(s). I'll provide an example for the first case. Ice cream flavors.
public enum IceCreamFlavors {
VANILLA, FRENCH_VANILLA, PEANUT_BUTTER, CHOCOLATE, CHOCOLATE_CHIP,
CHOCOLATE_CHIP_COOKIE, COOKIE_DOUGH, ICE_CREAM_CAKE, AMERICAN_DREAM,
VANILLA_CHOCOLATE_SWIRL, STRAWBERRY, MINT_CHOCOLATE_CHIP, OREOS_COOKIES_AND_CREAM;
public static IceCreamFlavors fromName(String name) {
for (IceCreamFlavors f : values()) {
if (f.name().replace('_', ' ').equalsIgnoreCase(name)) {
return f;
}
}
return IceCreamFlavors.VANILLA;
}
}
Then you can call it like
System.out.println("Which ice cream flavor do you want? ");
IceCreamFlavors flavor = IceCreamFlavors.fromName(input.nextLine());
And that way your logic for validation of the flavor it kept with-in the enum.
use:
private List<String> standardToppingList;
private List<String> deluxToppingList;
with Constructor containing:
standardToppingList = new Arraylist<>();
deluxToppingList = new Arraylist<>();
to add to the list, use:
standardToppingList.add(standardTopping);
deluxToppingList.add(deluxTopping);
and Display Using:
for(String s : deluxToppingList) {
System.out.println(s);
}
for(String s : standardToppingList) {
System.out.println(s);
}

Java dice game counter unable to add correctly

I wrote a dice game in java that rolls two dice and keeps score.
The entire game has a total of four classes but the problem I am facing is in my EyesHaveIt class.
It adds each turn to a total score but it is not calculating the math correctly.
I've tried to find what is causing it but with no success.
Can anyone help me find where the problem is?
public class EyesHaveIt {
Scanner kb = new Scanner(System.in);
private int turnScore;
private int computerTotalScore;
private int playerTotalScore;
private int computerTurnNumber;
private int playerTurnNumber;
public int roundPoints;
private String userName;
//Accepts a name value from PlayGame class.
public void init(String name) {
userName = name;
}
//This method starts the game with a computer turn.
public void playGame() {
computerTurn();
}
//Computers turn to roll the dice.
public void computerTurn() {
turnScore = 0;
System.out.println("Computer's turn: ");
while (turnScore < 20) {
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
//Checks users input(enter) to continue player turn.
public void enterToContinue() {
System.out.print("\nPress ENTER to continue ...");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
playerTurn();
}
//Players turn to roll the dice.
public void playerTurn() {
turnScore = 0;
System.out.println(userName + "'s turn:");
for (int i = 0; i < 5; i++) {
rollTheDice();
playerTurnNumber++;
getPlayerTotalScore(turnScore);
System.out.println("Roll again? (y/n) ");
char continueGame = kb.next().charAt(0);
continueGame = Character.toUpperCase(continueGame);
if (continueGame == 'Y') {
int test = 0;
} else {
getGameScore();
}
}
getGameScore();
computerTurn();
}
//Creates two dice from PairOfDice class and prints values rolled.
public void rollTheDice() {
PairOfDice dieOne = new PairOfDice();
PairOfDice dieTwo = new PairOfDice();
int die1 = dieOne.getDieOneValue();
int die2 = dieTwo.getDieOneValue();
System.out.println("\tRolled: " + die1 + " and " + die2);
whatWasRolled(die1, die2);
}
//Accepts int from rollTheDie and checks the value.
public void whatWasRolled(int die1, int die2) {
if (die1 == 1 && die2 == 1) {
System.out.println("\t Rolled snake eyes! All turn points will be doubled.");
roundPoints = (die1 + die2 * 2);
setScore(roundPoints);
} else if (die1 == 6 && die2 == 6) {
System.out.println("\t Rolled box cars! All points are gone now!");
roundPoints = 0;
setScore(roundPoints);
} else if (die1 == die2) {
System.out.println("\t Rolled double. . . lose all turn points.");
roundPoints = 0;
setScore(roundPoints);
} else {
roundPoints = die1 + die2;
setScore(roundPoints);
getTurnScore();
}
}
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = turnScore + roundPoints;
}
//Sets computer game score.
public void setComputerTotalScore(int turnScore) {
computerTotalScore = turnScore + computerTotalScore;
}
//Sets player game score.
public void setPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
}
//computerTotalScore accesor returns an int.
public int getComputerTotalScore() {
return computerTotalScore;
}
//playerTotalScore accesor returns an int.
public int getPlayerTotalScore(int turnScore) {
playerTotalScore = turnScore + playerTotalScore;
return playerTotalScore;
}
//Returns turnScore after roll.
public int getTurnScore() {
System.out.println("\tCurrent score for this turn:" + turnScore);
return turnScore;
}
//How the game ends and current game score is displayed.
public void getGameScore() {
System.out.println(
"CURRENT GAME SCORE: Computer: " + computerTotalScore + "\t" + userName + ": " + playerTotalScore);
if (computerTotalScore >= 150) {
System.out.println("Sorry, " + userName + " you got beat by the computer!");
System.exit(0);
} else if (playerTotalScore > 150) {
System.out.println(userName + ", Congratulations! You beat the computer!");
System.exit(0);
}
}
}
how are you?
I have made 3 alterations in 2 classes.
have a look to see if it will work for you.
//Computers turn to roll the dice.
public void computerTurn() {
computerTurnNumber = 0; // here
turnScore = 0;
System.out.println("Computer's turn: ");
while (computerTurnNumber < 20) { // here is the amount of time the dice will be rolled
rollTheDice();
computerTurnNumber++;
setComputerTotalScore(turnScore);
}
getGameScore();
enterToContinue();
}
and
//Sets turnScore from whatWasRolled.
public void setScore(int roundPoints) {
turnScore = roundPoints; //here, before it was accumulating the points of each turn
}

User inputted array is entirely the last input

When I execute this program, the canidateArray only stores the last user input as every variable in the array.
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class ArrayElection {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of candidates: ");
int loops = input.nextInt();
int loops2 = loops;
Canidate[] canidateArray = new Canidate[loops];
String canidatename;
int canidatevotes = 0;
int outputno = 1;
while (loops > 0){
System.out.println("Enter " + outputno +". name:");
canidatename = input.next();
System.out.println("Enter votes:");
canidatevotes = input.nextInt();
new Canidate(canidatename, canidatevotes);
loops = loops - 1;
outputno = outputno + 1;
}
if (canidateArray[0].getVotes() == canidateArray[1].getVotes()) {
System.out.println("The election is a tie between the following candidates: ");
System.out.println(canidateArray[0].getName() + " (" + canidateArray[0].getVotes() + " votes)");
System.out.println(canidateArray[1].getName() + " (" + canidateArray[1].getVotes() + " votes)");
System.out.println(canidateArray[2].getName() + " (" + canidateArray[2].getVotes() + " votes)");
}
else {
System.out.println("The winner is " + canidateArray[0].getName() + " with " + canidateArray[0].getVotes() + " votes!");
}
}
public static class Canidate {
private static String name;
private static int votes;
public Canidate(String name, int votes) {
this.name = name;
this.votes = votes;
}
public static String getName() {
return name;
}
public static int getVotes() {
return votes;
}
}
}
You don't store anything in the array. Fix :
while (loops > 0){
System.out.println("Enter " + outputno +". name:");
canidatename = input.next();
System.out.println("Enter votes:");
canidatevotes = input.nextInt();
loops = loops - 1;
canidateArray[outputno-1] = new Canidate(canidatename, canidatevotes);
outputno = outputno + 1;
}
But you'll have to fix your last part of code. You test canidateArray[0] vs canidateArray[1] while you can have
1 candidate, then it will trigger an IndexOutOfBoundsException
or more than 2 candidates

Randomly generated numbers won't work after while loop is applied

I am trying to make a combat sequence, but I need to repeat the actual combat. Yet, the HP and enemyHP won't seem to subtract from the randomly generated numbers to give the total after first loop.
I am sorry, if this doesn't make sense. I'm not really good at explaining things...
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class Hayyan {
public int hp = 100;
public int choice = 0;
public static void main(String[] args) {
combatHayyan bob = new combatHayyan();
Hayyan junl = new Hayyan();
while(junl.choice < 10){
System.out.println("Choose a weapon to attack with, type sword for a sword, or axe for an axe ");
bob.attack();
bob.defend();
System.out.println();
if(junl.hp < 0 || bob.enemyHP < 0){
junl.choice = 10;
}
}
}
}
class combatHayyan {
public int enemyHP = 50;
public int yourTotal;
public void attack(){
weapons weapon = new weapons();
Scanner bob = new Scanner(System.in);
switch(bob.nextLine()){
case "sword":
weapon.sword();
System.out.println("Enemy now has " + weapon.total + "HP left!");
break;
case "axe":
weapon.axe();
System.out.println("Enemy now has " + weapon.total + "HP left!");
break;
}
}
public void defend(){
Hayyan lost = new Hayyan();
Random bob = new Random();
int randomness = bob.nextInt(11) + 10;
yourTotal = lost.hp - randomness;
System.out.println("You now have " + yourTotal + "HP left!");
}
}
class weapons {
public int total;
public void sword(){
int bob = 5 + (int)(Math.random() * ((10 - 5) + 1));
combatHayyan llama = new combatHayyan();
total = llama.enemyHP - bob;
}
public void axe(){
int randomGenerate = 5 + (int)(Math.random() * ((10 - 5) + 1));
combatHayyan llama = new combatHayyan();
total = llama.enemyHP - randomGenerate;
}
}
Your question is little broad, but I believe you need to change this:
total = llama.enemyHP - bob;
with this:
total = total - bob;
Just initialize total to llama.enemyHP first. Same thing for defend, you are doing:
yourTotal = lost.hp - randomness;
and I believe you'd rather want:
yourTotal = yourTotal - randomness;
Otherwise, your variables are always recalculated at every pass in the loop.
With my recommandation, you need to refactore your code for it to make sense, but basically, you are not keeping the value modified with the random value, so you are re-doing the random calculation over and over.
EDIT:
You should consider refactoring your code and use a little more OO concepts. Take a look at this, I've refactored it without going too far from your design, so you can follow it and compare to your solution:
class Hayyan {
public static void main(String[] args) {
CombatHayyan combatHayyan = new CombatHayyan();
Scanner scanner = new Scanner(System.in);
while (combatHayyan.bothCombatantsAlive()) {
System.out.println("Choose a weapon to attack with, type sword for a sword, or axe for an axe ");
combatHayyan.attack(scanner);
combatHayyan.defend();
System.out.println();
}
scanner.close();
combatHayyan.printWinner();
}
}
class CombatHayyan {
public int enemyHP = 50;
public int yourHp = 100;
Weapons weapon = new Weapons();
public void attack(Scanner scanner) {
int damage = 0;
switch (scanner.nextLine()) {
case "sword":
damage = weapon.sword();
break;
case "axe":
damage = weapon.axe();
break;
}
enemyHP = enemyHP - damage;
System.out.println("Enemy now has " + enemyHP + "HP left!");
}
public void printWinner() {
String winner = yourHp>0?"You":"The enemy";
int hp = yourHp>0?yourHp:enemyHP;
System.out.println(winner + " won! with " + hp + "HP remaining");
}
public boolean bothCombatantsAlive() {
return enemyHP > 0 && yourHp > 0;
}
public void defend() {
Random random = new Random();
int randomness = random.nextInt(11) + 10;
yourHp = yourHp - randomness;
System.out.println("You now have " + yourHp + "HP left!");
}
}
class Weapons {
public int sword() {
return 5 + (int) (Math.random() * ((10 - 5) + 1));
}
public int axe() {
return 5 + (int) (Math.random() * ((10 - 5) + 1));
}
}

Why am I getting 1 as result after using "i" as my array index?

I've made a class named Car with methods that should resemble some functions of a real car. I'm trying to get the car's number of both the heaviest car and smallest car's engine.
As shown in my code below, you can see that I've done the validation using an index and then comparing that to "i". However, no matter what number I enter, I get "1" as result on both validations.
What could be wrong? I should be getting the number of the car instead of just "1".
Here is my code to get the heaviest car:
int weight = x[i].getweight();
if(weight > max) {
maxweight = weight;
maxIndex = i;
}
My Car class:
public class Car
{
private String color;
private int weight;
private int state;
private int fuel;
private int Maxspeed ;
private int engine;
public Car() {
this.color = "White";
this.weight = 1000;
this.state = 0;
this.fuel =0;
this.Maxspeed = 0;
this.engine = 0;
}
public Car (String color, int weight,
int state, int fuel, int Maxspeed
) {
this.color = color;
this.weight = weight;
this.state = state;
this.fuel = fuel;
this.Maxspeed = Maxspeed;
}
public String getColor() { return this.color; }
public int getweight() { return this.weight; }
public int getstate() { return this.state; }
public int getfuel() { return this.fuel; }
public int getMaxspeed() { return this.Maxspeed; }
public int getengine() { return this.engine; }
public void setColor( String color ){
this.color = color;
}
public void setweight( int weight ){
this.weight = weight;
}
public void setstate( int state ){
this.state = state;
}
public void setfuel( int fuel ){
this.fuel = fuel;
}
public void setMaxspeed( int Maxspeed ){
this.Maxspeed = Maxspeed;
}
public void setengine(int engine){
this.engine = engine;
}
public void showdata() {
System.out.println( "\nCar's color is: " + this.getColor() );
System.out.println( "Car's weight is: " + this.getweight() );
System.out.println( "State: " + this.getstate() );
System.out.println( "Fuel: " + this.getfuel());
System.out.println( "Max speed: " + this.getMaxspeed());
}
public void accelerate( int speed ){
if( this.getstate() == 0 || this.getstate() == 3 ||
this.getstate() == 4 || this.getMaxspeed() < speed )
{
System.out.println("\nCar cannot accelerate...");
}
else {
System.out.println("\nCar is accelerating...");
this.setfuel(this.getfuel()-2);
this.setstate(2);
if( this.getfuel() <= 0 ) {
this.setstate(4);
}
}
}
public void crash() {
this.setstate(3);
System.out.println("\nCrash!!!");
}
public void stop() {
this.setstate(1);
System.out.println("\nCar has stopped.");
}
public void addfuel(int fuel) {
if(this.getstate() == 0 || this.getstate() == 4){
this.setfuel(this.getfuel()+ fuel);
}
else {
System.out.println("You can't add fuel.");
}
}
public void repair() {
if(this.getstate() == 3){
this.setstate(1);
System.out.println("The car has been repaired");
}
else{
System.out.println("The car is not broken");
}
}
}
My Main:
import java.util.Scanner;
public class aaa {
public static void main (String args []) {
Car x[] = new Car[2];
int keep=1;
int counter = 0;
int counter_stopped = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int maxIndex = 0;
int maxweight = 0;
int index_engine = 0;
int min_engine = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i < x.length; i++) {
String color;
int weight;
int fuel;
int Maxspeed;
int engine;
x[i] = new Car();
System.out.print("\nEnter car color " + (i + 1) + ": ");
color = input.next();
System.out.print("Enter car weight " + (i + 1) + ": ");
weight = input.nextInt();
System.out.print("Enter car fuel " + (i + 1) + ": ");
fuel = input.nextInt();
System.out.print("Enter car max speed " + (i + 1) + ": ");
Maxspeed = input.nextInt();
System.out.print("Enter car engine weight " + (i + 1) + ": ");
engine = input.nextInt();
x[i].setColor(color);
x[i].setweight(weight);
x[i].getstate();
x[i].setfuel(fuel);
x[i].setMaxspeed(Maxspeed);
x[i].setengine(engine);
}
for(int i = 0; i < x.length; i++) {
int state;
System.out.print("\nEnter car state " + (i + 1) + ": ");
state = input.nextInt();
x[i].setstate(state);
while(state > 4 || state < 0){
System.out.print("state not valid.\nTry again: ");
state = input.nextInt();
x[i].setstate(state);
}
do {
keep = menu();
switch( keep ) {
case 1:
accelerate(x[i]);
break;
case 2:
stop(x[i]);
break;
case 3:
crash(x[i]);
break;
case 4:
addfuel(x[i]);
break;
case 5:
repair(x[i]);
break;
case 6:
x[i].showdata();
}
} while(keep != 7);
if(x[i].getstate() == 4 || x[i].getfuel() <= 0){
counter += 1;
}
if(x[i].getstate() == 1){
counter_stopped += 1;
}
int weight = x[i].getweight();
if(weight > max){
maxweight = weight;
maxIndex = i;
}
int weightengine = x[i].getengine();
if(weightengine < min){
min_engine = weightengine;
index_engine = i;
}
}
System.out.println("\nSUMMARY");
System.out.println("Amount of cars with no fuel: " + counter);
System.out.println("Amount of stopped cars: " + counter_stopped);
System.out.println("Heaviest car: " + maxIndex);
System.out.println("Car with the smallest engine: " + index_engine);
System.out.println("=============================================");
}
public static int menu() {
int option = 0;
Scanner s = new Scanner(System.in);
System.out.println("\n1. Accelerate Car ");
System.out.println("2. Stop Car ");
System.out.println("3. Crash Car ");
System.out.println("4. Add fuel ");
System.out.println("5. Repair ");
System.out.println("6. Show data ");
System.out.println("7. Exit ");
System.out.println("=============================================");
System.out.print("Choose an option : ");
option = s.nextInt();
System.out.println("=============================================");
return option;
}
public static void accelerate(Car myCar){
Scanner input = new Scanner(System.in);
int s;
System.out.print("Enter speed: ");
s = input.nextInt();
myCar.accelerate(s);
//myCar.showdata();
}
public static void stop(Car myCar){
myCar.stop();
}
public static void crash(Car myCar){
myCar.crash();
}
public static void addfuel(Car myCar){
int fuel;
Scanner input = new Scanner(System.in);
System.out.print("Amount to add: ");
fuel = input.nextInt();
myCar.addfuel(fuel);
}
public static void repair(Car myCar){
myCar.repair();
}
}
Now, when I compile and test which engine or car is smaller or heaviest, I get the number 1 as result.
The most obvious issue is
if(weight > max){
maxweight = weight;
You are comparing max and weight, but then seeting maxweight. Also, I suggest you prefer Math.max(int, int) and Math.min(int, int) like
max = Math.max(max, weight);
min = Math.min(min, weight);
Edit To store the index of the min and max value you could initialize max and min to 0 and loop from index 1 to x.length. That might look something like
int max = 0;
int min = 0;
for (int i = 1; i < x.length; i++) {
if (x[i].getweight() > x[max].getweight) {
max = i;
} else if (x[i].getweight() < x[min].getweight) {
min = i;
}
}

Categories