Simple turn-based game fight system - java

I am a beginner in Java. I am making a basic turn-based game, but I have problems with the fight system. I attack the randomly selected enemy with the chosen weapon until it dies, however I can't figure out how to decrease my HP.
I tried the following method in the Character class:
public void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
player.setHealth(myHealth-this.damage);
System.out.println("Your remaining HP: "+ myHealth);
It doesn't work, because the " player.setHealth()" is not reachable in the Character class.
How could I solve this? Should I make another class for the fight system?
Also, canI make my code simplier by using inheritance or interfaces?
Thanks in advance guys!
MAIN CLASS
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int size = 0;
public static void main(String[] args) {
int myHealth = 1000;
int myDamage = 5;
Scanner sc = new Scanner(System.in);
Character zombie = new Character("Zombie", 500, 10);
Character wolf = new Character("Wolf", 200, 30);
Character dragon = new Character("Dragon", 1000, 200);
Character bigDragon = new Character("Big Dragon", 2000, 400);
Character vampire = new Character("Vampire", 1000, 250);
ArrayList<Character> characterList = new ArrayList<>();
characterList.addAll(Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire
));
Weapon fist = new Weapon("Fist", 5);
Weapon sword = new Weapon("Sword", 50);
Weapon bow = new Weapon("Bow", 40);
Weapon crossBow = new Weapon("Crossbow", 35);
Weapon revolver = new Weapon("Revolver", 100);
ArrayList<Weapon> weaponList = new ArrayList<>();
weaponList.addAll(Arrays.asList(
fist,
sword,
bow,
crossBow,
revolver
));
size = characterList.size();
int whichCharacter = random();
for (int i = 0; i < characterList.size(); i++) {
System.out.println((i + 1) + ". character: " + characterList.get(random()).getName());
}
System.out.println("Your name!");
String myName = sc.nextLine();
Character player = new Character(myName, 1000, myDamage);
System.out.println("Your name: " + myName);
System.out.println("Your HP: " + myHealth);
System.out.println("Your attack power: " + myDamage);
System.out.println();
System.out.println();
System.out.println("You were attacked by a(n):");
System.out.println("Name: " + characterList.get(whichCharacter).getName());
System.out.println("HP: " + characterList.get(whichCharacter).getHealth());
System.out.println("Attack power: " + characterList.get(whichCharacter).getDamage());
System.out.println();
System.out.println("You attack with...");
System.out.println();
System.out.println("1. fist");
System.out.println("2. sword");
System.out.println("3. bow");
System.out.println("4. crossbow");
System.out.println("5. revolver");
int choice = sc.nextInt();
while (!characterList.get(whichCharacter).isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}
}
public static int random() {
int szam = (int) (Math.random() * size);
return szam;
}
}
CHARACTER CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Character {
private String name;
private int health;
private int damage;
private boolean dead = false;
public boolean isDead() {
return dead;
}
public void setDead(boolean dead) {
this.dead = dead;
}
public Character(boolean dead) {
this.dead = dead;
}
public Character(String name, int health, int damage) {
this.name = name;
this.health = health;
this.damage = damage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
// this.health = 0;
System.out.println(this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
System.out.println("Your remaining HP: "+ myHealth);
}
}}
WEAPON CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Weapon {
private String name;
private int weaponDamage;
public Weapon(String name, int weaponDamage) {
this.name = name;
this.weaponDamage = weaponDamage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeaponDamage() {
return weaponDamage;
}
public void setWeaponDamage(int weaponDamage) {
this.weaponDamage = weaponDamage;
}
}

I have made some changes in looping logic, I hope it would help :
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
player.attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}

Since you need an instance of player to call its methods, you could pass it as an input parameter, for example you could call the attack method like this:
characterList.get(whichCharacter).attack(player);
and modify it like this (simply replacing damageAmount and myHealth with the corresponding methods from Character):
public void attack(Character characterAttacked) {
if (characterAttacked.getDamage() >= this.health || characterAttacked.getHealth() <= 0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= characterAttacked.getDamage();
System.out.println("The remaining life of " + this.name + " is: " + this.health);
characterAttacked.setHealth(characterAttacked.getHealth() - this.damage);
System.out.println("Your remaining HP: "+ characterAttacked.getHealth());
}
}

As I tried to prepare an answer with a suggestion for a working attack method I found out, that your attack method does not work for me.
So here some general suggestions to improve your code:
Use an instance of Character for the player too.
pass that instance to the attack method.
Improve the use of lists (I will add an example below.)
use a Map with the user entered number as key instead of the switch statement.
Improved use of lists:
// Use the generic interface List instead of implementation class.
// You don't need extra ArrayList, just use the result of Arrays.asList
// - if you don't need to change the list afterwards.
List<Character> characterList =
Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire);
Use Map for weapons:
Map<Integer, Weapon> weapons = new HashMap<>();
weapons.put(1, fist);
weapons.put(2, sword);
// and so on - you get the idea
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
Weapon weapon = weapons.get(choice);
if (null == weapon) {
weapon = fist;
}
myDamage = weapon.getDamage();
// and here you can continue your code
}
Hope that above suggestions also help you a bit further.

Related

Making specific moves in a turn based fighting game

I'm trying to make a turn based fighting game in Java Eclipse. Right now there's nothing wrong with my code but I just needed help figuring out a way to add multiple attacks to each of my characters in the game.
This is my main method
public class Main {
public static Random generator = new Random();
public static void main(String[] args) {
String answer = "yes";
while(answer.equals("yes")) {
Character player1 = new Wraith();
Character player2 = new Paladin();
Scanner charInput = new Scanner(System.in);
System.out.println("Player1, Choose your character");
String choice = charInput.nextLine();
if(choice.equals("Paladin")) {
player1 = new Paladin();
}
if(choice.equals("Wizard")) {
player1 = new Wizard();
}
if(choice.equals("Wraith")) {
player1 = new Wraith();
}
System.out.println("Player2, Choose your character");
String choice2 = charInput.nextLine();
if(choice2.equals("Paladin")) {
player2 = new Paladin();
}
if(choice2.equals("Wizard")) {
player2 = new Wizard();
}
if(choice2.equals("Wraith")) {
player2 = new Wraith();
}
//player1.name = input("Player1 pick your character(Paladin, Wraith, Wizard)", charInput);
//player2.name = input("Player2 pick your character(Paladin, Wraith, Wizard)", charInput);
System.out.println(player1.name + " vs. " + player2.name);
System.out.println(player1.health + " vs. " + player2.health);
while (player1.isAlive() && player2.isAlive()) {
System.out.println(player1.name + ": " + player1.health);
System.out.println(player2.name + ": " + player2.health);
int damage;
damage = player1.attack(player2);
System.out.println(player1.name + " hits " + player2.name + " for " + damage);
damage = player2.attack(player1);
System.out.println(player2.name + " hits " + player1.name + " for " + damage);
}
if(player1.isAlive()) {
System.out.println(player1.name + " wins!");
} else if (player2.isAlive()) {
System.out.println(player2.name + " wins!");
} else {
System.out.println("It's a draw!");
}
}
}
private static String input(String string, Scanner charInput) {
return null;
}
}
This is one of my character classes
public class Wizard extends Character {
public int dexterity = 25;
public static Random generator = new Random();
public Wizard(){
super();
this.name = "Wizard";
this.strength = 10;
this.defense = 8;
this.health = 95;
}
public int attack(Character target){
boolean criticalHit =Main.generator.nextInt(150) < dexterity;
int damage = this.strength * 2;
if(criticalHit){
damage *= 2;
System.out.println("*** Critical Hit ***");
}
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
}```
And this is my main character class
public class Character {
public String name;
public int strength;
public int health;
public int defense;
public int takeDamage(int damage){
int damageTaken = damage - this.defense;
this.health -= damageTaken;
return damageTaken;
}
public int attack(Character target){
int damage = this.strength * 2;
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
public boolean isAlive(){
return health > 0;
}
}```
also I'm new to coding and stack overflow so and suggestions on how to make my posts make more sense or something like that is much appreciated
nice implemention of a battle system.
when a Character performs an attack you choose which attack that should be and execute:
public int attack(Character target){
AttackMode mode = determineAttackMode(target); // the charater chooses what kind of attack he will execute during this attack
switch(mode){
case AttackMode.DOUBLESTRIKE: return attackDoubleStrike(target);
case AttackMode.BURST: return attackBurst(target);
default: return attackDefault(target); // your previously implemented method attack(target)
}
}
The AttackMode is an Enum class:
enum AttackMode {DEFAULT, DOUBLESTRIKE, BURST}
i'm not sure how double damage is dealt, so this is a guess here
public int attackDoubleStrike(Character target){
int firstStrike = attackDefault(target);
int secondStrike = attackDefault(target);
return firstStrike + secondStrike;
}

Java Card game: my Card game removes 2 cards from the deck instead of 1

Run this code so you can play it aswell.
Rules: Guess the next it's higher or lower card. if you guessed right get a score, if you guessed wrong the game ends.
the issue is that "Deck.getCards().size()" size of the deck removes 2 cards each time. I believe that the card that I print if guessed right does show another card instead of the one I had to guess before.
Can someone see what is wrong.
Bonus question: Ace in my game is the highest value card. But I somehow managed to lose while guessing lower when having a ace (maybe this has to do with that I believe I had ace because of what I outprint) if someone can help out with this one I would be so thankfull..
package CardGame;
import java.util.Scanner;
import java.util.*;
public class Game {
// score int
private static int score;
// currentCard : Card
private static Card currentCard;
// Next Card
private static Card nextCard;
// Scanner
private static Deck deck;
private static Scanner sc = new Scanner(System.in);
// Main
public static void main(String[] args) {
deck = new Deck();
currentCard = deck.getNextCard();
Game.gameTurn();
}
// get turn method
public static void gameTurn() {
// System.out.println(Deck.getCards().size());
score = 0;
System.out.print("your current card is " + currentCard.getName() + " is it higher or lower? > ");
while (true) {
String answer = sc.nextLine();
Card nextCard = deck.getNextCard();
if (answer.equals("higher") && nextCard.isHigherOrEqual(currentCard)) {
correct();
} else if (answer.equals("lower") && !nextCard.isHigherOrEqual(currentCard)) {
correct();
} else {
gameOver();
break;
}
}
}
// correct method
public static void correct() {
score++;
System.out.println("You are right! your score is: " + score);
System.out.println(Deck.getCards().size() + " total cards");
nextCard = Deck.getNextCard();
System.out.println("your current card is " + nextCard.getName());
}
// Game over Method
public static void gameOver() {
System.out.println("you lost");
System.out.println("total score is " + score + "!");
System.out.println(Deck.getCards().size() + " total cards");
}
}
package CardGame;
import java.util.ArrayList;
import java.util.Collections;
public class Deck {
// cards = Card = new ArrayList<>()
private static ArrayList<Card> cards = new ArrayList<>();
// Deck Method
public Deck() {
for (int i = 0; i < 4; i++) {
String suits;
switch (i) {
// hart
case 0:
suits = "Hearts";
break;
// ruit
case 1:
suits = "Diamonds";
break;
// schoppen
case 2:
suits = "Spades";
break;
// klaveren
case 3:
suits = "Clubs";
break;
default:
suits = "";
break;
}
for (int j = 2; j <= 10; j++) {
int value = j;
String name = j + " of " + suits;
Card c = new Card(suits, name, value);
cards.add(c);
}
// add 1.3 tot 1.11
Card jack = new Card(suits, "Jack of " + suits, 11);
cards.add(jack); // JACK
Card queen = new Card(suits, "Queen of " + suits, 12);
cards.add(queen); // QUEEN
Card king = new Card(suits, "King of " + suits, 13);
cards.add(king); // KING
Card ace = new Card(suits, "Ace of " + suits, 14);
cards.add(ace); // ACE
}
// 1.11 shuffle cards
Collections.shuffle(cards);
}
// getNextCard() : Card
public static Card getNextCard() {
Card nextCard = cards.remove(0);
return nextCard;
}
// getCards() : ArrayList <card>
public static ArrayList<Card> getCards() {
return cards;
}
}
package CardGame;
public class Card {
// Suit String
private String suit;
// Name String
private String name;
// Value int
private int value;
// Card constructor
public Card(String suit, String name, int value) {
this.value = value;
this.name = name;
this.suit = suit;
}
public int getValue() {
return value;
}
// toString Method
public String toString() {
return suit;
}
public String getName() {
return name;
}
// isHigherorEqual Method
public boolean isHigherOrEqual(Card c) {
if (this.value >= c.getValue()) {
return true;
} else {
return false;
}
}
}
You are using getNextCard twice before checking the result. So it will remove 2 cards. If you want to update the current card, change the nextCard to currentCard in Correct method.
public static void correct() {
score++;
System.out.println("You are right! your score is: " + score);
System.out.println(Deck.getCards().size() + " total cards");
currentCard = Deck.getNextCard();
System.out.println("your current card is " + currentCard.getName());
}
Remove nextCard = Deck. .... from correct method.
Move
String answer = sc.nextLine();
Card nextCard = deck.getNextCard();
System.out.println("your current card is " + nextCard.getName());

Java - Store the changing int variable

So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .
public void attack(Player somePlayer) {
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
int remainingHealth = totalHealth - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
}
}
But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same, I guess the problem is in this line :
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
I guess everytime I run the code
somePlayer.getHitpoints()
takes the inserted integer from constructor and that's the problem.
I need to figure out the way to store the remaining health in a variable somehow
Player class :
public class Player implements ISavable{
private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;
public Player(String name, int damage , int hitPoints , int strength) {
this.name = name;
this.damage = damage;
this.weapon = "Sword";
this.hitPoints = hitPoints;
this.strength = strength;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHitPoints() {
return hitPoints;
}
public void setHitPoints(int hitPoints) {
this.hitPoints = hitPoints;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public int getTotalHealth() {
return totalHealth;
}
public void setTotalHealth(int totalHealth) {
this.totalHealth = totalHealth;
}
#Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", hitPoints=" + hitPoints +
", strength=" + strength +
", weapon='" + weapon + '\'' +
'}';
}
#Override
public List<String> write() {
List<String> values = new ArrayList<String>();
values.add(0, this.name);
values.add(1, "" + this.hitPoints);
values.add(2, "" + this.strength);
values.add(3, "" + this.weapon);
values.add(4,"" + this.damage);
return values;
}
#Override
public void read(List<String> savedValues) {
if (savedValues != null && savedValues.size()>0){
this.name = savedValues.get(0);
this.hitPoints = Integer.parseInt(savedValues.get(1));
this.strength = Integer.parseInt(savedValues.get(2));
this.weapon = savedValues.get(3);
}
}
public void attack(Monster someMonster){
int health = someMonster.getHitPoints();
int remainingHealth = health - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("You killed the monster !!!");
} else {
System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
System.out.println("Monsters remaining health is - " + remainingHealth);
}
if (someMonster.isDead()){
this.hitPoints = 100;
this.strength = 50;
}
}
public void healPlayer(Player somePlayer){
int hp = somePlayer.getHitPoints();
hp += 10;
System.out.println("You healed the player for 10hp , your current hp is " + hp);
}
}
You are not updating the value of totalHealth, you initialize it everytime that attack() method is called, so you always have the same Health.
You can solve it putting out of the attack() method the line:
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
EDIT:
public void attack(Player somePlayer) {
somePlayer.totalHealth = somePlayer.totalHealth - this.damage;
if (somePlayer.totalHealth.equals(0) || somePlayer.totalHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (somePlayer.totalHealth - somePlayer.getStrength()));
}
}
On Player create a function updateHealth(int newHealth) that sets the variable returned from getHitPoints() to newHealth. Then just append somePlayer.updateHealth(somePlayer.getHitPoints() - damage); at the end of the attack function.
You should have a representation of health, defining in Player totalHealth.
You may use a method which calculate the total health (cause your player could get an item that increases strenght or an item that allow heal you).
Then you should use another variable in Player, remainingHealth and initialize it as remainingHealth = totalHealth
public class Player {
float totalHealth;
float remainingHealth;
...
public Player(...) {
this.remainingHealth = this.totalHealth;
...
}
...
}
When you want decrease the health of your player you should use remainingHealth.
public void attack(Player somePlayer) {
somePlayer.remainingHealth -= this.damage;
if (somePlayer.remainingHealth <= 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked ...");
System.out.println("Your remaining health is - " + somePlayer.remainingHealth);
}
}

How to print the array index of an object class?

I have a somewhat big code and I'm triying to print the slot number of an array from an object class that resulted to be the one with the highest weight.
On my main I have declared my array like this:
Car x[] = new car[2];
Now when triying to get which car has the highest weight I've made this validation inside a for loop
//.getweight obtains the weight of each car
if(x[i].getWeight() > max){
max = x[i].getWeight();
}
That code gives me the actual weight number of the heaviest car, but what I want to print is the actual car number. The comparing works but I can't find a way to just print the slot that corresponds to the heaviest car.
UPDATE with full code:
My object car:
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 array index would be i
The actual car would be x[i]
You need to hold on to a reference to the index to the heaviest car. In this example I am using maxIndex.
float maxWeight = 0;
int maxIndex = 0;
for (int i = 0; i < x.length; i++) {
float weight = x[i].getWeight();
if (weight > max) {
maxWeight = weight;
maxIndex = i;
}
}
System.out.println("Slot of heaviest car: " + maxIndex);

I'm getting an error here when I call my getChoice() method, and I don't know why

I'm getting an error where I call my getChoice() method, its saying variable footballTeam2 is already defined in the main method, why is that? Also am I calling my other method correctly?
Thanks in advance guys, really could use some help.
import java.util.Scanner;
public class FootballGame {
static Scanner keyboard = new Scanner(System.in);
static int arewedone = 0;
static String choice;
static FootballTeam team;
public static void main(String[] args) {
FootballTeam footballTeam1;
FootballTeam footballTeam2;
System.out.print("Enter a name for a team:");
footballTeam1 = new FootballTeam(keyboard.nextLine(), 0);
System.out.print("Enter a name for another team:");
footballTeam2 = new FootballTeam(keyboard.nextLine(), 0);
do{
System.out.println("Game Score:");
System.out.println(footballTeam1.getName() + ":" + footballTeam1.getScore());
System.out.println(footballTeam2.getName() + ":" + footballTeam2.getScore());
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
handleTeamScore(team);
}while(arewedone == 0);
}
public static String getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2) {
String input;
do {
System.out.println("Select an option:");
System.out.println("A:" + footballTeam1 + " scored");
System.out.println("B:" + footballTeam2 + " scored");
System.out.println("C: game ended.");
System.out.println("?:");
input = keyboard.nextLine();
if (input.equalsIgnoreCase("A")) {
choice = (footballTeam1 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = (footballTeam2 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("C")) {
System.out.println("Game Over");
arewedone++;
}
} while (!input.equals("A") && !input.equals("B") && !input.equals("C"));
return choice;
}
public static void handleTeamScore(FootballTeam team) {
int points;
do {
System.out.println("How many points were scored?");
System.out.print("?: ");
points = keyboard.nextInt();
if ((team.addScore(points)) == true) {
arewedone++;
} else {
System.out.println("That was an invalid option. Please try again.");
System.out.println("Hints:");
System.out.println("Touchdown = 6 points");
System.out.println("Field Goal = 3 points");
System.out.println("Safety = 2 points");
System.out.println("Extra Point = 1 point");
}
} while (arewedone == 0);
}
}
Here's my other class with the addscore method and getters and setters.
public class FootballTeam {
private String name;
private int score;
public static int TOUCHDOWN = 6;
public static int FIELD_GOAL = 3;
public static int SAFETY = 2;
public static int TWO_POINT_CONVERSION = 2;
public static int EXTRA_POINT = 1;
public FootballTeam(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public boolean addScore(int points) {
if (points == TOUCHDOWN || points == FIELD_GOAL || points == SAFETY || points == TWO_POINT_CONVERSION || points == EXTRA_POINT) {
score = points + score;
return true;
} else {
return false;
}
}
}
Change the method call
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
to this:
choice = getMenuChoice(footballTeam1, footballTeam2);
EDIT:
You need to initialize FootballTeam team before calling handleTeamScore(team);:
team = new FootballTeam(...);
handleTeamScore(team);
Change this code block of getMenuChoice:
if (input.equalsIgnoreCase("A")) {
choice = (footballTeam1 + "");
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = (footballTeam2 + "");
arewedone = 0;
to this :
public static String getMenuChoice(...){
...
if (input.equalsIgnoreCase("A")) {
choice = "footballTeam1";
arewedone = 0;
} else if (input.equalsIgnoreCase("B")) {
choice = "footballTeam2";
arewedone = 0;
...
}
Now replace these two statements in main:
choice = getMenuChoice(footballTeam1, footballTeam2);
handleTeamScore(team);
to this:
choice = getMenuChoice(footballTeam1, footballTeam2);
if(choice != null) {
if(choice.equals("footballTeam1")){
team = footballTeam1;
}
if(choice.equals("footballTeam2")){
team = footballTeam2;
}
handleTeamScore(team);
}
You are calling your method wrongly
you should call it like this
choice = getMenuChoice1( footballTeam1, footballTeam2);
by calling it like this
choice = getMenuChoice(FootballTeam footballTeam1, FootballTeam footballTeam2);
you confusing compiler whether you are calling a method or declaring a new one. We dont require to type the type while calling the method its implicit always

Categories

Resources