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

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);
}
}

Related

How to read .csv file in Java?

I'm trying to read .csv file which can run as per the below options given in program which are:
Enter 1 to output all the information for all of the products in the inventory.
Enter 2 to output all the information for all of the products under a particular category (Bakery, Meat, Produce, Deli, Cleaning).
Enter 3 to add more products to the inventory
My .csv file is below:
MEAT,Chicken breast,14.50,8,2020-03-03,1
PRODUCE,Royal Gala apple,2.5,20,2020-03-20,1.0
MEAT,Chicken kebabs honey soy,9.0,6,2020-03-03,0.48
PRODUCE,Broccoli,2.00,33,2020-03-10,0.4
MEAT,Burger patties,10.00,8,2020-03-08,0.4
MEAT,Lamb loin chop,28.00,12,2020-03-05,0.5
PRODUCE,Nectarine,7.00,9,2020-03-09,1.8
MEAT,Beef premium mince,12.50,16,2020-02-27,0.6
PRODUCE,Avacado,2.35,10,2020-03-07,0.2
PRODUCE,Green grapes,7.00,5,2020-03-01,1.0
I'm able to run the first option and display all the information. I need help in option 2 and option 3.
This is my Main class:
package InventorySystem;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/**
* All that is remaining to do is task 4 & 5:
* 1. Implement the file reading/writing to the csv file.
* hint:- Just save to the csv file on exiting (when the user presses "q") by incrementally
* printing each item in the LocalStore inventory (eg. store.inventory.get(i).toString()).
* Do the opposite when you first run the program, the very first thing program should do
* is read the csv file and incrementally add each line in the file as a new object into the
* inventory ArrayList.
* 2. Implement exception handling for the file reading/writing
* 3. Implement data validation in case the user enters incorrect data
*/
public class Main
{
private static String name,
veganStr = "";
private static double basePrice,
weight;
private static int quantity,
day,
month,
year;
private static boolean vegan = false;
private static LocalStore store = new LocalStore("My Food Store","35 Queen Street",35500);
//method to get the mandatory information to create an Inventory item
private static void getMandatory()
{
System.out.print("Enter the item's name --> ");
name = Keyboard.readInput();
System.out.print("Enter the item's base price --> ");
basePrice = Double.parseDouble(Keyboard.readInput());
System.out.print("Enter the item quantity --> ");
quantity = Integer.parseInt(Keyboard.readInput());
}
//method to get the optional items required for Deli & Bakery items
private static void getOptional()
{
System.out.println("Enter the expiry date --> ");
String date = Keyboard.readInput();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.print("Enter the item's weight --> ");
weight = Double.parseDouble(Keyboard.readInput());
}
//method to get the vegan details
private static void getVegan()
{
System.out.print("Is the item suitable for vegans? Y/N --> ");
veganStr = Keyboard.readInput();
if(veganStr.equalsIgnoreCase("y"))
{
vegan = true;
}
}
private static void addDeliItem()
{
getMandatory();
getOptional();
getVegan();
//add the new item
store.inventory.add(new Deli(name,basePrice,quantity,day,month,year,weight,vegan));
}
private static void addBakeryItem()
{
getMandatory();
getOptional();
getVegan();
store.inventory.add(new Bakery(name,basePrice,quantity,day,month,year,weight,vegan));
}
private static void addProduceItem()
{
getMandatory();
getOptional();
store.inventory.add(new Produce(name,basePrice,quantity,day,month,year,weight));
}
private static void addMeatItem()
{
getMandatory();
getOptional();
store.inventory.add(new Meat(name,basePrice,quantity,day,month,year,weight));
}
private static void addCleaningItem()
{
getMandatory();
store.inventory.add(new Cleaning(name,basePrice,quantity));
}
private static void mainMenu() throws FileNotFoundException {
Scanner menuOptionIn = new Scanner(System.in);
Scanner addOptionIn = new Scanner(System.in);
String menuAnswer,
addOption;
boolean cont = true;
while (cont) {
//show the menu to the user
System.out.println("\n---MAIN MENU---\nEnter 1 to output all the information for all of the products in the inventory\n" +
"Enter 2 to output all the information for all of the products under a particular category\n" +
"Enter 3 to add more products to the inventory\n" +
"Enter q to quit the program");
//read the user's input
menuAnswer = menuOptionIn.nextLine();
if (menuAnswer.equals("1") || menuAnswer.equals("2") || menuAnswer.equals("3")) {
switch (menuAnswer) {
case "1":
//output info for all products
store.printAll();
break;
case "2":
//output info for particular category
System.out.println("\nWhat category item would you like to view?\n" +
"Enter 1 for Deli\n" +
"Enter 2 for Bakery\n" +
"Enter 3 for Produce\n" +
"Enter 4 for Meat\n" +
"Enter 5 for Cleaning\n" +
"Enter r to return to the menu");
addOption = addOptionIn.nextLine();
switch (addOption) {
case "1":
store.printType("Deli");
break;
case "2":
store.printType("Bakery");
break;
case "3":
store.printType("Produce");
break;
case "4":
store.printType("Meat");
break;
case "5":
store.printType("Cleaning");
break;
case "r":
//return to the main menu
break;
default:
break;
}
break;
case "3":
//add products
//ask the user to select item group they wish to add
System.out.println("\nWhat category item would you like to add?\n" +
"Enter 1 for Deli\n" +
"Enter 2 for Bakery\n" +
"Enter 3 for Produce\n" +
"Enter 4 for Meat\n" +
"Enter 5 for Cleaning\n" +
"Enter r to return to the menu");
addOption = addOptionIn.nextLine();
switch (addOption) {
case "1":
addDeliItem();
break;
case "2":
addBakeryItem();
break;
case "3":
addProduceItem();
break;
case "4":
addMeatItem();
break;
case "5":
addCleaningItem();
break;
case "r":
//return to the main menu
break;
default:
break;
}
break;
}
} else if (menuAnswer.equalsIgnoreCase("q")) {
System.exit(0);
}
}
}
public static void main(String[] args) throws FileNotFoundException {
mainMenu();
//print all test objects
store.printAll();
//print only Meat
store.printType("Meat");
}
}
This is my LocalStore class where changes needs to be done under addProduct and printType.
package InventorySystem;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class LocalStore
{
private String supermarketName,
location;
private int maxProducts;
public ArrayList<Inventory> inventory = new ArrayList<>(maxProducts);
public LocalStore(String n,String l,int max)
{
this.supermarketName = n;
this.location = l;
this.maxProducts = max;
}
//add product to inventory array
public void addProduct(Inventory inv)
{
if(inventory.size()<maxProducts)
{
inventory.add(new Inventory(inv));
System.out.println("Inventory Successfully added");
}
else if(inventory.size() == maxProducts)
{
System.out.println("Inventory full");
}
}
public void printAll() throws FileNotFoundException {
/*for(int i=0;i<inventory.size();++i)
{
System.out.println(inventory.get(i).toString());*/
final String FILE_NAME = "productList.csv";
Scanner scnr = new Scanner(new FileInputStream(FILE_NAME));
while (scnr.hasNextLine()) {
System.out.println(scnr.nextLine());
}
scnr.close();
}
public void printType(String type)
{ //check for Deli
if(type.equalsIgnoreCase("Deli"))
{
System.out.println("Deli Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Deli)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Bakery
else if(type.equalsIgnoreCase("Bakery"))
{
System.out.println("Bakery Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Bakery)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Produce
else if(type.equalsIgnoreCase("Produce"))
{
System.out.println("Produce Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Produce)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Meat
else if(type.equalsIgnoreCase("Meat"))
{
System.out.println("Meat Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Meat)
{
System.out.println(inventory.get(i).toString());
}
}
}
//check for Cleaning
else if(type.equalsIgnoreCase("Cleaning"))
{
System.out.println("Cleaning Items...");
for(int i=0;i<inventory.size();++i)
{
if(inventory.get(i) instanceof Cleaning)
{
System.out.println(inventory.get(i).toString());
}
}
}
//inform user no matches exist
else
{
System.out.println("No items match your search...");
}
}
//set and get supermarket details
public void setSupermarketName(String n)
{
this.supermarketName = n;
}
public String getSupermarketName()
{
return this.supermarketName;
}
public void setSupermarketLocation(String l)
{
this.location = l;
}
public String getSupermarketLocation()
{
return this.location;
}
public void setMaxProducts(int m)
{
this.maxProducts = m;
}
public int getMaxProducts()
{
return this.maxProducts;
}
}

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());

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);
}
}
}

Java Suit Application using enums, methods and user input updated

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());
}
}
}

Java receipt program not displaying results

I have created a simple application that reads a series of products * quantity sold and generates a final order receipt that includes the sold item name, quantity and total for each item as well as the total for the whole receipt (including 6% sales tax). I feel that I accomplished this, except I cannot test the application as nothing is printing to the "receipt" AKA ContentPane. Below are the three classes I used.
PRODUCT class:
public class Product
{
private int coffeeQTY;
private int teaQTY;
private int bagelQTY;
private int muffinQTY;
private double tax;
private double total;
private double price;
private int productNOM;
public Product()
{
total=price=0.00;
productNOM=coffeeQTY=teaQTY=bagelQTY=muffinQTY=0;
}
//setters
public void setcoffeeQTY(int c)
{
coffeeQTY += c;
}
public void setteaQTY(int t)
{
teaQTY += t;
}
public void setbagelQTY(int b)
{
bagelQTY += b;
}
public void setmuffinQTY(int m)
{
muffinQTY += m;
}
//getters
public int getcoffeeQTY()
{
return coffeeQTY;
}
public int getteaQTY()
{
return teaQTY;
}
public int getbagelQTY()
{
return bagelQTY;
}
public int getmuffinQTY()
{
return muffinQTY;
}
public double getTAX()
{
return tax;
}
public double getTotal()
{
return total;
}
private double coffeePrice;
private double teaPrice;
private double bagelPrice;
private double muffinPrice;
public void inputOrder()
{
for(int i = 0; i <= 3; i++)
{
String order = JOptionPane.showInputDialog("Product 1: Coffee $3.65 "
+ "\nProduct 2: Tea $2.45 "
+ "\nProduct 3: Bagel $1.50 "
+ "\nProduct 4: Muffins $1.85 "
+ "\nEnter the number of the product you would like to order. Enter -1 when your order is complete: ");
productNOM = Integer.parseInt(order);
boolean done = false;
switch(productNOM)
{
case 1:
coffeePrice = 3.65;
String cQTY = JOptionPane.showInputDialog("Enter the quantity of Coffee you would like to order: ");
setcoffeeQTY(Integer.parseInt(cQTY));
break;
case 2:
teaPrice = 2.45;
String tQTY = JOptionPane.showInputDialog("Enter the quantity of Tea you would like to order: ");
setteaQTY(Integer.parseInt(tQTY));
break;
case 3:
bagelPrice = 1.50;
String bQTY = JOptionPane.showInputDialog("Enter the quantity of Bagels you would like to order: ");
setbagelQTY(Integer.parseInt(bQTY));
break;
case 4:
muffinPrice = 1.85;
String mQTY = JOptionPane.showInputDialog("Enter the quantity of the Muffins you would like to order: ");
setmuffinQTY(Integer.parseInt(mQTY));
break;
default:
done = true;
break;
}
total += coffeePrice * coffeeQTY + teaPrice * teaQTY + bagelPrice * bagelQTY + muffinPrice * muffinQTY;
if(!done)
{
tax = ((coffeePrice * coffeeQTY) * 0.06) + ((teaPrice * teaQTY) * 0.06) + ((bagelPrice * bagelQTY) * 0.06) + ((muffinPrice * muffinQTY) * 0.06);
total = (coffeePrice * coffeeQTY) + (teaPrice * teaQTY) + (bagelPrice * bagelQTY) + (muffinPrice * muffinQTY) + tax;
continue;
}
else
{
break;
}
}
}
public void draw(Graphics g)
{
g.drawString("Coffee $3.65 x" +getcoffeeQTY(), 25, 100);
g.drawString("Tes $2.45 x" +getteaQTY(), 25, 125);
g.drawString("Bagel $1.50 x" +getbagelQTY(), 25, 150);
g.drawString("Muffin $1.85 x" +getmuffinQTY(), 25, 175);
g.drawString("Tax(6%): " +getTAX(), 25, 225);
g.drawString("Total: " +getTotal(), 25, 250);
}
}
SALES class
public class Sales extends JComponent
{
private Product merch;
public Sales(Product m)
{
merch = m;
}
public void printSales(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
merch.draw(g2);
}
}
PRINTSALES class
public class PrintSales
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Product merch = new Product();
merch.inputOrder();
JFrame frame = new JFrame();
frame.setSize(500, 750);
frame.setTitle("Coffee Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.WHITE);
Sales store = new Sales(merch);
frame.add(store);
frame.setVisible(true);
}
}
I don't know if its related to the addition of the tax field, but it looks like the printSales(...) function is never called in, so nothing will be drawn.

Categories