Java Suit Application using enums, methods and user input updated - java

I have got through all of this paper except the last part(Part 5) I have attached the picture of the paper for the part I am struggling with above.
When running my application tester, when I press 3, nothing happens. Does anyone know why? the code of my classes is below. NOTE: the updateBrand() method which is called in the tester in the makeChangeToSuit method is in the morningSuit and suit classes.
I would appreciate any help on this matter.
package SuitProg;
import java.util.Scanner;
public abstract class Suit {
//instance variables
private String Colour;
private double dailyCost;
private int trouserLength;
private int jacketChestSize;
private boolean available;
protected double totalPrice;
//constructor
public Suit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available) {
super();
Colour = colour;
this.dailyCost = dailyCost;
this.trouserLength = trouserLength;
this.jacketChestSize = jacketChestSize;
this.available = available;
this.totalPrice = totalPrice;
}
//accessors & mutators
public String getColour() {
return Colour;
}
public double getDailyCost() {
return dailyCost;
}
public int getTrouserLength() {
return trouserLength;
}
public int getJacketChestSize() {
return jacketChestSize;
}
public boolean getAvailability() {
return available;
}
public double getTotalPrice() {
return totalPrice;
}
public void setDailyCost(double dailyCost) {
this.dailyCost = dailyCost;
}
public void setTrouserLength(int trouserLength) {
this.trouserLength = trouserLength;
}
public void setJacketChestSize(int jacketChestSize) {
this.jacketChestSize = jacketChestSize;
}
public void setAvailability(boolean available) {
this.available = available;
}
//methods
public String toString() {
return " Suit [ Colour: " + getColour() + ", Daily Cost: " + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability();
}
public void calcTotalPrice (int numDaysHired) {
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
}
public String printDailyCost() {
getDailyCost();
return "£" + String.format("%.2f", getDailyCost());
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(null);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
import java.util.Scanner;
public class MorningSuit extends Suit implements Brandable {
//instance variables
private boolean boutonniere;
private boolean topHat;
public Brand brand;
//constructor
public MorningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean boutonniere, boolean topHat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.boutonniere = boutonniere;
this.topHat = topHat;
}
//accessors & mutators
public boolean getBout() {
return boutonniere;
}
public boolean getTopHat() {
return topHat;
}
public void setBout(boolean boutonniere) {
this.boutonniere = boutonniere;
}
public void setTopHat(boolean topHat) {
this.topHat = topHat;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
//methods
public String toString() {
return "Morning Suit [ Boutonniere " + getBout() + " TopHat " + getTopHat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice(int numDaysHired) {
if (getBout()) {
totalPrice = totalPrice + 3;
}
if (getTopHat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (numDaysHired * getDailyCost());
System.out.println("The morning suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Morning Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
updateBrand(input);
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
public void updateBrand(Scanner input) {
boolean valid = false;
int selection;
System.out.println("The list of available brands are below:");
System.out.println("1 - " + Brand.Highstreet);
System.out.println("2 - " + Brand.TedBaker);
System.out.println("3 - " + Brand.FrenchConnection);
do {
System.out.println("Please enter the number of the Brand you wish to change.");
if (input.hasNextInt()) {
selection = input.nextInt();
if (selection < 1 || selection > 3) {
valid = false;
System.out.println("Please enter a number betwen 1 and 3");
} else
valid = true;
System.out.println("You have selected number: " + selection);
if (selection == 1) {
System.out.println("Please enter the changes you want to make");
System.out.println("New brand name : ");
//
}
}
} while (!valid);
}
}
package SuitProg;
public enum Brand {
Highstreet,TedBaker,FrenchConnection
}
package SuitProg;
public interface Brandable {
public String getBrand();
}
package SuitProg;
import java.util.Scanner;
public class EveningSuit extends Suit implements Brandable {
//variables
private boolean cufflinks;
private boolean waistcoat;
public Brand brand;
public EveningSuit(String colour, double dailyCost, int trouserLength, int jacketChestSize, boolean available, boolean cufflinks, boolean waistcoat) {
super(colour, dailyCost, trouserLength, jacketChestSize, available);
this.cufflinks = cufflinks;
this.waistcoat = waistcoat;
this.brand = Brand.Highstreet;
}
//accessors & mutators
public boolean getCuffs() {
return cufflinks;
}
public boolean getWaistcoat() {
return waistcoat;
}
public void setCuffs(boolean cufflinks) {
this.cufflinks = cufflinks;
}
public void setWaistcoat(boolean waistcoat) {
this.waistcoat = waistcoat;
}
//methods
public String toString() {
return "Evening Suit [ Cufflinks " + getCuffs() + " Waistcoat " + getWaistcoat() + " Colour: " + getColour() + ", Daily Cost: £" + String.format("%.2f", getDailyCost())
+ "\nTrouser Length: " + getTrouserLength() + ", Jacket Chest Size: " + getJacketChestSize()
+ " Is it available? " + getAvailability() + "]";
}
public void calcTotalPrice (int numDaysHired) {
if (getCuffs()) {
totalPrice = totalPrice + 5;
}
if (getWaistcoat()) {
totalPrice = totalPrice + 10;
}
totalPrice = totalPrice + (getDailyCost() * numDaysHired);
System.out.println("The evening suit was hired for " + numDaysHired + " days.");
System.out.println("The total cost for the hire was: £" + String.format("%.2f", totalPrice));
}
public String getBrand() {
return "The brand of this Evening Suit is " + brand.toString().toLowerCase();
}
public void makeChange(Scanner input) {
boolean valid = false;
do {
System.out.println("Are you sure you want to change the branding of a suit?");
String response = input.nextLine().toLowerCase();
if (response.equalsIgnoreCase("Y")) {
valid = true;
System.out.println("You can not change the brand name of an evening suit.");
}
else
if (response.equalsIgnoreCase("N")) {
valid = true;
System.exit(0);
break;
}
} while (!valid);
}
}
package SuitProg;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester05 {
public static void main(String[] args) {
//create arrayList of suits
ArrayList<Suit> suits = new ArrayList<Suit>();
//create morningSuit object
MorningSuit MorningSuit1 = new MorningSuit("Black", 80.00, 32, 36, true, true, false);
MorningSuit1.setBrand(Brand.FrenchConnection);
//create evening suit
EveningSuit EveningSuit1 = new EveningSuit("White", 70.25, 34, 36, true, true, true);
//add suits to arrayList
suits.add(MorningSuit1);
suits.add(EveningSuit1);
//print all details of arrayList
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
System.out.println(MorningSuit1.getBrand());
System.out.println(EveningSuit1.getBrand());
printMenu(suits);
}
public static void printMenu(ArrayList<Suit> suits) {
Scanner input = new Scanner(System.in);
System.out.println("----------------Suit Hire-----------------");
System.out.println("What would you like to do?");
System.out.println("\n1)Display all suits\n2)Display available suits\n3)Change Suit brand\n4)Finished");
System.out.println("Please select an option: ");
int selection = input.nextInt();
if (selection == 1) {
displayAllSuits(suits);
} else
if (selection == 2) {
displayAllSuits(suits);
}
else
if (selection ==3) {
makeChangeToSuits(suits, input);
}
else
if (selection ==4) {
System.out.println("You are now exitting the system.");
System.exit(0);
}
}
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (int i = 0; i > suits.size(); i ++) {
suits.get(i).updateBrand(input);
}
}
public static void displayAllSuits(ArrayList<Suit> suits) {
for (Suit eachSuit : suits) {
System.out.println(eachSuit .toString()+"\n");
}
}
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (int i = 0; i > suits.size(); i++) {
if (suits.get(i).getAvailability()) {
System.out.println(suits.get(i).toString());
}
}
}
}

The problem is in your makeChangeToSuits method when you iterate the list. It should look like:
public static void makeChangeToSuits(ArrayList<Suit> suits, Scanner input) {
for (Suit suit : suits) {
suit.updateBrand(input);
}
}
Also, your displayAvailableSuits method should look like:
public static void displayAvailableSuits(ArrayList<Suit> suits) {
for (Suit suit : suits) {
if (suit.getAvailability()) {
System.out.println(suit.toString());
}
}
}

Related

Check and retain the previous object instead of creating a new one

I am new to Java.
I created a banking system where user can pay their utility bills. I want to keep that status of the bills whether it is paid or not in Bills class. But whenever user wants to go to pay their bills and it creates a new object which vipes the previous data stored in that object. I want something to check if an object already exists it uses that but if it does not exists then create an object and use that. Please do let me know if it is possible.
Look at case 2 where it makes a new object everytime.
import java.util.Scanner;
import java.util.Random;
public class Main {
static boolean isAccount = false;
public static void main(String[] args) {
Menu menu = new Menu(isAccount);
menu.showMenu();
menu.take();
}
}
class Menu {
int option = 0;
boolean isAccount;
double money;
Scanner input = new Scanner(System.in);
public Menu(boolean isAccount) {
this.isAccount = isAccount;
}
public void showMenu() {
System.out.println("Choose your option: \n1. Create an Account\n2. Pay Bills\n3. Banking");
}
public void take() {
if (input.hasNextInt()) {
int opt = input.nextInt();
this.option = opt;
}
System.out.println("Option value: " + this.option);
navigate();
}
public void navigate() {
while (this.option != -1) {
switch (this.option) {
case 1:
if (!isAccount) {
Scanner nameInput = new Scanner(System.in);
System.out.print("Enter your name: ");
String name;
name = nameInput.next();
Random rand = new Random();
int id, number;
do {
number = rand.nextInt(99999);
id = number;
} while (number < 10000);
Scanner accountInput = new Scanner(System.in);
System.out.print("Do you want current account (true/false): ");
boolean isCurrent = accountInput.nextBoolean();
Account acc = new Account(name, id, isCurrent);
this.money = acc.getMoney();
acc.print();
isAccount = true;
} else {
System.out.println("You already have an account!");
}
break;
case 2:
if (isAccount) {
System.out.println("Money: " + this.money);
Bill bill = new Bill(this.money);
bill.showBills();
bill.selectBill();
this.money = bill.getMoney();
} else {
System.out.println("Please make an account before you pay the bill!");
showMenu();
take();
}
break;
case 3:
if (isAccount) {
Banking bank = new Banking(money);
bank.showMenu();
bank.takeOption();
this.money = bank.getMoney();
System.out.println("\nNew Bank Balance: " + this.money + "\n");
} else {
System.out.println("Please make an account before you do banking");
showMenu();
take();
}
}
this.showMenu();
this.take();
}
}
}
here's the bills class
import java.util.Scanner;
import java.util.Random;
class Bill {
class Paid {
boolean electricity, water, gas, internet = false;
}
int option;
double money;
Paid paidBills = new Paid();
public Bill(double money) {
this.money = money;
}
public void showBills () {
System.out.println("\nWhich bill do you want to pay?");
System.out.println("1. Electricity Bill\n2. Gas Bill\n3. Water Bill\n4. Internet Bill\n5. See Bills Status");
}
public void selectBill() {
Scanner input = new Scanner(System.in);
option = input.nextInt();
navigate(this.option);
}
public void navigate(int option) {
switch (option) {
case 1:
Electricity ebill = new Electricity(this.money);
double tempEBill = Math.floor(ebill.makeBill());
ebill.showBill(tempEBill);
this.money = ebill.pay(tempEBill);
ebill.receipt(tempEBill, this.money);
paidBills.electricity = true;
break;
case 2:
Gas gbill = new Gas(money);
double tempGBill = Math.floor(gbill.makeBill());
gbill.showBill(tempGBill);
this.money = gbill.pay(tempGBill);
gbill.receipt(tempGBill, this.money);
paidBills.gas = true;
break;
case 3:
Water wbill = new Water(money);
double tempWBill = Math.floor(wbill.makeBill());
wbill.showBill(tempWBill);
this.money = wbill.pay(tempWBill);
wbill.receipt(tempWBill, this.money);
paidBills.water = true;
break;
case 4:
Internet ibill = new Internet(money);
double tempIBill = Math.floor(ibill.makeBill());
ibill.showBill(tempIBill);
this.money = ibill.pay(tempIBill);
ibill.receipt(tempIBill, this.money);
paidBills.internet = true;
break;
case 5:
showPaidBills();
break;
}
}
public void showPaidBills() {
System.out.println("\nElectricty: " + paidBills.electricity + "\nWater: " + paidBills.water + "\nGas: " + paidBills.gas + "\nInternet: " + paidBills.internet + "\n");
}
public double getMoney() {
return this.money;
}
}
class Electricity {
double money;
static double bill;
public Electricity(double money) {
this.money = money;
}
public double makeBill() {
Random rand = new Random();
bill = rand.nextDouble() * 1000;
return bill;
}
public void showBill(double tempBill) {
System.out.println("\nElectricity Bill: " + tempBill);
}
public double pay(double tempBill) {
return money - tempBill;
}
public void receipt(double tempBill, double money) {
System.out.println("Bill paid amount = " + tempBill);
System.out.println("Remaining Amount in Bank = " + money + "\n");
}
}
class Water extends Electricity {
public Water(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nWater Bill: " + tempBill);
}
}
class Gas extends Electricity {
public Gas(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nGas Bill: " + tempBill);
}
}
class Internet extends Electricity {
public Internet(double money) {
super(money);
}
public void showBill(double tempBill) {
System.out.println("\nInternet Bill: " + tempBill);
}
}

Having issues with code, How can I reinitialize my player

So when I run the code(there are 5 more files that go with this) It is supposed to run a card game up to 10 rounds and determine a winner. However I only get up to the first round and then it terminates. I got some help with what might be wrong. I need to reinitialize my player so it stops giving me a
NullPointerException
import java.util.ArrayList;
import java.util.Random;
public class Game
{
private static deckOfCards deck = new deckOfCards();
private static ArrayList<Card> table = new ArrayList<>();
private static Card topCard;
private static Player p1 = new Player("Player One");
private static Player p2 = new Player("Player Two");
private static Player currentPlayer = p1;
private static int rounds = 1;
private static boolean gameOver = false;
public static void startGame()
{
System.out.println("Starting game now:");
dealCards();
chooseFirstPlayer();
playRounds();
declareWinner();
}
public static void dealCards()
{
for (int i = 0; i < 26; i++)
{
p1.takeCard(deck.deal());
p2.takeCard(deck.deal());
}
}
public static void chooseFirstPlayer()
{
Random r = new Random();
int n = r.nextInt(2);
if (n == 1)
{
Player temp = p1;
p1 = p2;
p2 = temp;
}
}
public static void playRounds()
{
while (rounds <= 10 && (gameOver == false))
{
System.out.println("Round " + rounds);
System.out.println();
showHand();
playRound();
rounds++;
}
}
public static void playRound()
{
boolean suitMatch = false;
Card cardToPlay;
if ((p1.handSize() == 52) || (p2.handSize() == 52))
{
gameOver = true;
}
while (suitMatch == false)
{
cardToPlay = currentPlayer.playCard();
table.add(cardToPlay);
suitMatch = checkSuitMatch();
if (suitMatch == false)
switchCurrentPlayer();
}
collectCards();
System.out.println();
try
{
Thread.sleep(500);
}
catch (InterruptedException e){
}
}
public static void switchCurrentPlayer()
{
if (currentPlayer == p1)
currentPlayer = p2;
else if (currentPlayer == p2)
currentPlayer = p1;
}
public static boolean checkSuitMatch()
{
int tableSize = table.size();
int lastSuit;
int topSuit;
if (tableSize < 2)
{
return false;
}
else
{
lastSuit = table.get(tableSize - 1).getSuit();
topSuit = table.get(tableSize - 2).getSuit();
}
if (lastSuit == topSuit)
{
System.out.println();
System.out.println(currentPlayer.getName() + " wins the round!");
System.out.println();
return true;
}
return false;
}
public static void collectCards()
{
System.out.print(currentPlayer.getName() + " takes the table (" + table.size() + "): ");
displayTable();
for (int i = 0; i < table.size(); i++)
{
Card cardToTake = table.get(i);
currentPlayer.takeCard(cardToTake);
}
table.clear();
}
public static void displayTable()
{
for (int i = 0; i < table.size(); i++)
{
if (table.get(i) != null)
{
System.out.print(table.get(i).getName() + " ");
}
}
System.out.println();
System.out.println();
}
public static void showHand()
{
p1.showHand();
p2.showHand();
}
public static void declareWinner()
{
if (p1.handSize() > p2.handSize())
{
System.out.println(p1.getName().toUpperCase() + " wins " + "by having " + p1.handSize() + " cards!");
}
else if (p2.handSize() > p1.handSize())
{
System.out.println(p2.getName().toUpperCase() + " wins " + "by having " + p2.handSize() + " cards!");
}
else
{
System.out.println("It's a draw.");
}
System.out.println();
}
public static void main(String[] args)
{
startGame();
}
}
Here is my player class just incase:
public class Player
{
private Hand hand; //for the player's hand
private String name;
//Constructors
public Player(String name)
{
hand = new Hand();
this.name = name;
}
//prints and determines the card the player will play
public Card playCard()
{
Card playerCard = hand.playCard();
System.out.println(String.format("%5s", name) + playerCard.getName());
return playerCard;
}
//takes the card if player can match
public void takeCard(Card card)
{
hand.addCard(card);
}
public String getName()
{
return name;
}
//how the hand of player
public void showHand()
{
System.out.println(name + " hand " + hand.getSize() + ":");
hand.show();
System.out.println();
}
//get the size of players' hand
public int handSize()
{
return hand.getSize();
}
}

OOP How do I add defeated enemy's money to main character's bag?

I'm almost done with this java game project. I just have to add a defeated enemy's money to the main character's bag. I also have to add weapons and armor if they are better than the main character's weapons and armor. How do I add the enemy's money to the main character's money? In my mind, main_ch.getBag().getMoney() = main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney(); should work, but it doesn't.
Here is my main class:
import java.util.Scanner;
import Character.Character;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("> Welcome to The Game Project <");
System.out.println("\n >> Input Main Character Name: ");
String main_name = scanner.nextLine();
System.out.println(">> Input Main Character Power: ");
int main_power=scanner.nextInt();
System.out.println(">> Input Main Character Hp: ");
int main_hp=scanner.nextInt();
System.out.println("----------------------------------------------------");
Character main_ch=new Character (main_hp,main_power,main_name);
show_status(main_ch);
check_bag(main_ch);
Character enemies[]=new Character [10];
enemies[0]= new Character("Werewolf");
enemies[1]= new Character("Vampire");
enemies[2]= new Character("Alien");
enemies[3]= new Character("Witch");
enemies[4]= new Character("Ghost");
enemies[5]= new Character("Skeleton");
enemies[6]= new Character("Zombie");
enemies[7]= new Character("Demon");
enemies[8]= new Character("Mummy");
enemies[9]= new Character("Dragon");
boolean check = false;
int dead_count=0;
while(true) {
Random rnd=new Random();
int selected = rnd.nextInt(enemies.length); //random enemy selected
System.out.println();
System.out.println(">>>>> An enemy has appeared! <<<<<");
while(enemies[selected].getHp()>0) {
System.out.println();
System.out.println(">>>>> "+enemies[selected].getName()+" wants to fight!");
show_status(enemies[selected]);
check_bag(enemies[selected]);
System.out.println();
System.out.println(">> What do you want to do?");
System.out.println("\t1. Fight!");
System.out.println("\t2. Use skill.");
System.out.println("\t3. Check your stats.");
int input = scanner.nextInt();
if(input==1) {
int damageToEnemy = main_ch.hit_point();
int damageTaken = enemies[selected].hit_point();
enemies[selected].hp -= damageToEnemy;
main_ch.hp -= damageTaken;
if(enemies[selected].hp <= 0) {
enemies[selected].hp=0;
dead_count=dead_count+1;
main_ch.level=main_ch.level+1; //gain one level after enemy defeated
System.out.println(">> You defeated the enemy and gained a level!");
// The below code also doesn't work.
int pickUpMoney = main_ch.getBag().getMoney();
pickUpMoney=main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney();
System.out.println();
System.out.println("You found "+enemies[selected].getBag().getMoney()+" dollars. You now have "+main_ch.getBag().getMoney()+" dollars in your bag."); //take defeated enemy's money
for(int i = 0; i<4; i++) {
if(enemies[selected].getWeapon().getPower() > main_ch.getWeapon().getPower()) {
main_ch.getBag().getWeaponArray()[i]=enemies[selected].getBag().getWeaponArray()[i];
System.out.println("You found better weapons! They have been added to your bag.");
}
}
for(int i = 0; i<4; i++) {
if(enemies[selected].getArmor().getDefense()>main_ch.getArmor().getDefense()) {
main_ch.getBag().getArmorArray()[i]=enemies[selected].getBag().getArmorArray()[i];
System.out.println("You found better armor! They have been added to your bag.");
}
}
break;
}
System.out.println("\n>> You caused "+ damageToEnemy +" damage to the enemy! Their hp is now "+ enemies[selected].hp+".");
System.out.println(">> You received "+ damageTaken +" damage from the enemy! Your hp is now "+main_ch.hp+".");
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
else if(input==2) {
if(main_ch.getSkill()>0 && main_ch.getMp()>0) {
main_ch.useSkill();
System.out.println("\t>> You used a skill. Your hit point increased to "+main_ch.hit_point()+". Your MP decreased to "+main_ch.getMp()+".");
}
else {
if(main_ch.getSkill()<=0) {
System.out.println("You have no skill points left.");
}
else{
System.out.println("\t>> Your MP is too low to use skill.");
}
}
}
else if(input==3) {
System.out.println();
show_status(main_ch);
check_bag(main_ch);
}
else {
System.out.println(">> You have entered an invalid key.");
}
}
if(dead_count==enemies.length) {
check=true;
}
if(check) {
System.out.println();
System.out.println(">>>>>>>>>> You won! Congratulations, you defeated all of your enemies! <<<<<<<<<");
break;
}
if(main_ch.hp <=0) {
System.out.println();
System.out.println(">> Oh no! You died! Better luck next time. Thanks for playing!");
System.out.println();
break;
}
}
}
public static void show_status(Character character) {
System.out.println("----------------- Character Status -----------------");
System.out.println("\tCharacter Name:\t\t"+character.getName());
System.out.println("\tCharacter HP:\t\t"+character.getHp());
System.out.println("\tCharacter Power:\t"+character.getPower());
System.out.println("\tCharacter Defense:\t"+character.getDefense());
System.out.println("\tCharacter MP:\t\t"+character.getMp());
System.out.println("\tCharacter Level:\t"+character.getLevel());
System.out.println("\tCharacter Hit Point:\t"+character.hit_point());
System.out.println("\tCharacter Skill:\t"+character.getSkill());
System.out.println("\tWeapon Name:\t\t"+character.getWeapon().getName());
System.out.println("\tWeapon Power:\t\t"+character.getWeapon().getPower());
System.out.println("\tArmor Name:\t\t"+character.getArmor().getName());
System.out.println("\tArmor Defense:\t\t"+character.getArmor().getDefense());
System.out.println("----------------------------------------------------");
}
public static void check_bag(Character character) {
System.out.println("-------------------- Bag Status --------------------");
System.out.println("\tMoney:\t\t\t$"+ character.getBag().getMoney());
for(int i = 0; i<4; i++) {
System.out.println("\tWeapon Name/Power:\t"+ character.getBag().getWeaponArray()[i].getName()+" // "+character.getBag().getWeaponArray()[i].getPower());
}
for(int i = 0; i<4; i++) {
System.out.println("\tArmor Name/Defense:\t"+ character.getBag().getArmorArray()[i].getName()+" // "+character.getBag().getArmorArray()[i].getDefense());
}
System.out.println("----------------------------------------------------");
}
}
Here is my Character class:
package Character;
import java.util.Random;
import Equipment.*;
public class Character {
private Armor armor = new Armor();
private Weapon weapon = new Weapon();
private Bag bag = new Bag();
public static String server_name = "CS172";
public int hp, power, defense, mp, level, skill;
private String name;
Random rnd=new Random();
public Character(String name) {
this.name=name;
Random rnd=new Random();
this.hp=rnd.nextInt(500)+1;
this.power=rnd.nextInt(100)+1;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public Character(int hp, int power, String name) {
this.hp=hp;
this.power=power;
this.name=name;
this.defense=rnd.nextInt(100)+1;
this.mp=rnd.nextInt(50)+1;
this.level=1;
this.skill=5;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public int getMp() {
return mp;
}
public void setMp(int mp) {
this.mp = mp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getName() {
return name;
}
public int damage(int enemy_power) {
int damage = enemy_power - this.defense;
if(damage<0){ //avoid healing by damage
damage=0;
}
this.hp=this.hp - damage;
if(this.hp<0) { //avoid negative hp
this.hp = 0;
}
return damage;
}
public Armor getArmor() {
return armor;
}
public void setArmor(Armor armor) {
this.armor = armor;
}
public Weapon getWeapon() {
return weapon;
}
public void setWeapon(Weapon weapon) {
this.weapon = weapon;
}
public int hit_point() {
int total_power = this.power + this.weapon.getPower();
return total_power;
}
//------------------------------------------------------why isn't this increasing the hit point at all?
public int useSkill() {
this.mp=this.mp-1;
this.skill--;
return this.hit_point()+30;
}
public int getSkill() {
return skill;
}
public Bag getBag() {
return bag;
}
public void setBag(Bag bag) {
this.bag = bag;
}
public class Bag{
Weapon weaponArray[] = new Weapon[4];
Armor armorArray[] = new Armor[4];
int money = 150;
public Bag(){
for(int i=0; i<weaponArray.length; i++) {
weaponArray[i] = new Weapon();
armorArray[i] = new Armor();
}
}
public Weapon[] getWeaponArray() {
return weaponArray;
}
public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
this.weaponArray[yourWeaponIndex] = enemyWeapon;
}
public Armor[] getArmorArray() {
return armorArray;
}
public void setArmorArray(Armor[] armorArray) {
this.armorArray = armorArray;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
}
You are calling an accessor method like it will also set, which it doesn't. Try something like this:
main_ch.getBag().setMoney(main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney());

Im getting errors with some methods

I'm writing this java class which is the TUI for the Class loyaltyCard, However, I'm facing some errors with the methods below. Would appreciate any help, Thanks.
public void addLoyalty Card
public void ShowAllLoyaltyCards (it should print details of all loyaltycards with a space between each)
public void showLoyaltyCard (print out loyaltycard with the choose card number, if unsuccessful "message"
Here is my code:
import java.util.ArrayList;
import java.util.Scanner;
public class LoyaltyCardTUI
{
private LoyaltyCardList loyaltyCardList;
private Scanner myScanner;
public LoyaltyCardTUI()
{
myScanner = new Scanner(System.in);
LoyaltyCardList loyaltyCardList = new LoyaltyCardList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
**public void addLoyaltyCard(**)
{
loyaltyCardList.addLoyaltyCard(new LoyaltyCard());
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addLoyaltyCard();
else
if ( command == 2 )
getNumberOfLoyaltyCards();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfLoyaltyCards()
{
int command = myScanner.nextInt();
System.out.println("We have" + loyaltyCardList.getNumberOfLoyaltyCards() + "loyaltyCards");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
private void removeLoyaltyCard()
{
System.out.print("Enter card number : ");
String cardNumber = myScanner.nextLine();
if (loyaltyCardList.removeLoyaltyCard(cardNumber))
System.out.println("LoyaltyCard with card number " + cardNumber + " removed from class list");
else
System.out.println("LoyaltyCard with card number " + cardNumber + " not found");
}
**public void showAllLoyaltyCards()**
{
for(LoyaltyCard loyaltyCard : loyaltyCards)
{
loyaltyCard.printCustomerDetails();
System.out.println();
}
}
**public void showLoyaltyCard()**
{
for (LoyaltyCard loyaltyCard : loyaltyCards)
{
if (cardNumber.equals(loyaltyCard.getCardNumber()))
{
return System.out.println(loyaltyCard);
}
else
{
return System.out.println("Could not find loyalty card for card number"+cardNumber);
}
}
}
private void unknownCommand(int command)
{
System.out.println("Invalid Command : "+ command);
}
}

How to scan and respond to a user's input?

Creating a simple ATM menu with few options on it.
Want to know how to let user inputs something to select the options, and then the codes can respond to the input.
For example, "readLine(string)"
Following is my code:
public class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("Log In Account");
mainMenu.addOption("Deposit Check");
mainMenu.addOption("Help");
mainMenu.addOption("Quit");
mainMenu.display();
}
}
You can read the user Input with Scanner class. And then with switch statement do your required actions:
import java.util.Scanner;
class Menu
{
private String menuText;
private int optionCount;
public Menu()
{
menuText = "";
optionCount = 0;
}
public void addOption(String option)
{
optionCount = optionCount + 1;
menuText = menuText + optionCount + ") " + option + "\n";
}
public void display()
{
System.out.println(menuText);
}
}
public class MenuDemo{
public MenuDemo()
{
}
public static void main(String[] args)
{
Menu mainMenu = new Menu();
mainMenu.addOption("1. Log In Account");
mainMenu.addOption("2. Deposit Check");
mainMenu.addOption("3. Help");
mainMenu.addOption("4. Quit");
mainMenu.display();
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice: ");
String i = input.nextLine();
switch(i){
case "1":
//do something
System.out.println("User Entered 1 : " + i);
break;
case "2":
//do something
System.out.println("User Entered 2 : " + i);
break;
case "3":
//do something
System.out.println("User Entered 3 : " + i);
break;
case "4":
//do something
System.out.println("User Entered 4 : " + i);
break;
default:
System.out.println("Quit" + i);
}
}
}

Categories