Is there any way to use the video class in my code - java

I am unable to use the video class in my program.My code i running fine but according the question i should make use of the video class
But I'am getting the desired output without using it
import java.util.Scanner;
class Video{
String videoName;
boolean checkout;
int rating;
Video(String name){
videoName=name;
}
String getName(){
return videoName;
}
void doCheckout(){
}
void doReturn(){
}
void receiveRating(int rating){
this.rating=rating;
}
int getRating(){
return rating;
}
boolean getCheckout(){
return checkout;
}
}
videoStore extends the video class but there is no use with methods of video class the videoStore array values are resetting after every execution i dont know why
class VideoStore extends Video{
String videoStore[]=new String[100];
int rating[]=new int[100];
boolean status[]=new boolean[100];
int i=0,ind=0,len=-1;
VideoStore(String name) {
super(name);
}
void addVideo(String name){
videoStore[i]=name;
status[i]=false;
i++;
len++;
}
void doCheckout(String name){
if(len>=0){
int index=index(name);
status[index]=true;
}
else{
System.out.println("Nothig in inventory");
}
}
void doReturn(String name){
if(len>=0){
int index=index(name);
status[index]=false;
}
else{
System.out.println("Nothing in inventory");
}
}
void receiveRating(String name,int rating){
if(len>=0){
int index=index(name);
this.rating[index]=rating;
}
else{
System.out.println("Nothing in inventory");
}
}
void listInventory(){
if(len!=-1){
for(int p=0;p<=len;p++){
System.out.println(videoStore[p]+"\t"+status[p]+"\t"+rating[p]);
}
}
else{
System.out.println("nothing in inventory");
}
}
int index(String name){
for (int i = 0; i < videoStore.length; i++) {
if(videoStore[i].equals(name)){
return i;
}
}
return -1;
}
}
this is the main method
public class VideoLauncher {
public static void main(String[] args) {
String yn="y";
int option=0;
String videoName="";
VideoStore vs=new VideoStore(videoName);
Scanner sc=new Scanner(System.in);
do{
System.out.println("1.Add video");
System.out.println("2.Checkout video");
System.out.println("3.Return video");
System.out.println("4.recieve rating");
System.out.println("5.List inventory");
System.out.println("6.Exit");
System.out.println("please enter the option from 1..6");
option=sc.nextInt();
switch(option){
case 1:
System.out.println("please enter the video name");
videoName=sc.next();
Video v=new Video(videoName);
vs.addVideo(videoName);
System.out.println("video added successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 2:
System.out.println("please enter the name of the video to checkout");
videoName=sc.next();
vs.doCheckout(videoName);
System.out.println("Video "+videoName+" checkedout successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 3:
System.out.println("please enter the name of the video to return");
videoName=sc.next();
vs.doReturn(videoName);
System.out.println("Video "+videoName+" returned successfully");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 4:
System.out.println("enter the videoname");
videoName=sc.next();
System.out.println("enter the rating");
int rating=sc.nextInt();
vs.receiveRating(videoName,rating);
System.out.println("rating "+rating+" for video"+videoName+" recorded");
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 5:
vs.listInventory();
System.out.println("do you want to continue(y) else (n)");
yn=sc.next();
break;
case 6:
yn="n";
System.out.println("exiting");
break;
default :
System.out.println("please enter proper option");
}
}while(yn.equals("y"));
}
}

I am not going to give you the whole code but just get you started.
When VideoStore extends Video you are saying, VideoStore is a Video which is wrong, what you want to say is VideoStore has Videos. What you need is a list of Videos in your VideoStore
So your VideoStore should look something like that:
class VideoStore {
Video[] videos = new Video[100];
void addVideo(String name) {
Video v = new Video(name);
for(int i=0; i<videos.length; i++) {
if(videos[i] == null) {
videos[i] = v;
break;
}
}
}
void doCheckout(String name) {
int index = index(name);
videos[index].setCheckout(true);
}
void doReturn(String name) {
// your code
}
void receiveRating(String name, int rating) {
// your code
}
void listInventory() {
// your code
}
int index(String name) {
// your code
}
}
And to your interrogation:
the videoStore array values are resetting after every execution i dont know why
this is normal, they are only in memory and will be wiped out once the program terminates.

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 Java How do I check an array against another array and replace the data if the other array has higher numbers?

I am trying to check the selected enemy's weapons and armor to see if they are better than the main character's. So, I want to check each one by one, and if the enemy's are better I want to set the main character's weapon equal to the enemy's to basically take it and it to the main character's bag. Everything I have tried so far has been checking to see if one weapon is better and replacing all weapon regardless if the others are better or not. Is there a way I can check each individually?
I have four classes. Main. Character. Weapon. Armor. This is the part of the main class where I am trying to switch:
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) {
// originally using int damageToEnemy = rnd.nextInt(main_ch.hit_point());
// originally using int damageTaken = rnd.nextInt(enemies[selected].hit_point());
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!");
main_ch.getBag().setMoney(main_ch.getBag().getMoney() + enemies[selected].getBag().getMoney());//take defeated enemy's money
System.out.println();
System.out.println("\t>> You found "+enemies[selected].getBag().getMoney()+" dollars. You now have "+main_ch.getBag().getMoney()+" dollars in your bag.");
if(enemies[selected].getWeapon().getPower() > main_ch.getWeapon().getPower()) { //check to see if enemy's weapons have higher power
for(int i = 0; i<4; i++) {
main_ch.getBag().setWeaponArray(i, enemies[selected].getBag().getWeaponArray()[i]); //replace weapons if they are better
}
System.out.println("\t>> You found better weapons! They have been added to your bag.");
}
if(enemies[selected].getArmor().getDefense() > main_ch.getArmor().getDefense()) { //check to see if enemy's armor is better
for(int i = 0; i<4; i++) {
main_ch.getBag().setArmorArray(i, enemies[selected].getBag().getArmorArray()[i]); //replace armor if it is better
}
System.out.println("\t>> 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("----------------------------------------------------");
}
}
This is the Character class:
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;
}
public int useSkill() {
this.mp=this.mp-1;
this.skill--;
this.power =this.power + 30;
return hit_point();
}
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(int yourArmorIndex, Armor enemyArmor) {
this.armorArray[yourArmorIndex] = enemyArmor;
}
// public void setArmorArray(Armor[] armorArray) {
// this.armorArray = armorArray;
// }
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
}
I am doing this for a class, and we wrote part of the code in class with the professor. I have a feeling I am supposed to use this somehow, but I don't even really understand what it is doing:
public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
this.weaponArray[yourWeaponIndex] = enemyWeapon;
}
Can someone explain this to me please?
Weapons class:
package Equipment;
import java.util.Random;
public class Weapon {
private String name;
private int power;
Random rnd = new Random();
public Weapon() {
this.name="Weapon #" + rnd.nextInt(20);
this.power=rnd.nextInt(50)+1;
}
public Weapon(String name) {
this.name=name;
this.power=rnd.nextInt(50)+1;
}
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getName() {
return name;
}
}
Armor class:
import java.util.Random;
public class Armor {
private String name;
private int defense;
Random rnd = new Random();
public Armor() {
this.name="Armor #"+rnd.nextInt(10);
this.defense=rnd.nextInt(10)+1;
}
public Armor(String name) {
this.name=name;
this.defense=rnd.nextInt(10)+1;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
public String getName() {
return name;
}
}
Based on the code you are providing
public void setWeaponArray(int yourWeaponIndex, Weapon enemyWeapon) {
this.weaponArray[yourWeaponIndex] = enemyWeapon;
}
This method sets the current weapon of the bag (Your object here is the bag) to another enemyWeapon using the index of the element in the array weaponArray[] . But, since your array length is 4, I believe you have to call it 4 times to make the 4 weapons in the bag.
main_ch.getBag().setWeaponArray(enemies[selected].getBag().getWeaponArray());
In this line, you are not specifying the index (You normally have 2 parameters for the method setWeapon(int yourWeaponIndex, Weapon enemyWeapon)
It should be something like this :
main_ch.getBag().setWeaponArray(i ,enemies[selected].getBag().getWeaponArray());
i is the index of the weapon to change.
Example
main_ch.getBag().setWeaponArray(0 ,enemies[selected].getBag().getWeaponArray() );
This line only changes the first weapon if the enemy's weapon is better.
Instead of replacing the whole bag array just replace the weapon at the specific index in the loop.
You are almost there... That method that you wanted to use is exactly used for what you want. It is a method that requires two things. The position of your weapon to be replaced (yourWeaponIndex) and the item to replace it with (enemyWeapon). The weapons loop you are replacing the whole bag instead of the weapon in question.
for(int i = 0; i<4; i++) { //loop through your items one by one
for(int j = 0; j<4; j++) { //loop through enemy items one by one
//compare item 1 to all 4 enemies items (order 16 comparison - 4 x 4 comparisons)
if(enemies[selected].getBag().getWeaponArray()[j].getPower() > main_ch.getBag().getWeaponArray()[i].getPower()) { //check to see if enemy's weapons have higher power
//put stronger enemy weapon (j) in your bag
main_ch.getBag().setWeaponArray(i, enemies[selected].getBag().getWeaponArray()[j]);
//put your weaker weapon (i) in enemy bag
enemies[selected].getBag().setWeaponArray(j, main_ch.getBag().getWeaponArray()[i]);
//alert that items have changed
System.out.println("\t>> You found better weapons! They have been added to your bag.");
}
}
}
For the purpose of interest and learning
for(int k = 0; k<4; k++) { //loop through your items one by one
for(int l = 0; l<4; l++) { //loop through enemy items one by one
//compare item 1 to all 4 enemies items (order 16 comparison - 4 x 4 comparisons)
if(enemies[selected].getBag().getArmorArray()[l].getDefense() > main_ch.getBag().getArmorArray()[k].getDefense()) { //check to see if enemy's armor has higher power
//put stronger enemy armor in your bag
main_ch.getBag().setArmorArray(k, enemies[selected].getBag().getArmorArray()[l]);
//put your weaker armor in enemy bag
enemies[selected].getBag().setArmorArray(l, main_ch.getBag().getArmorArray()[k]);
//alert that items have changed
System.out.println("\t>> You found better weapons! They have been added to your bag.");
}
}
}
See the working code:
https://onlinegdb.com/rkg3n7ICH

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

Searching Item ArrayList by Property

I have an ArrayList of Objects/Items with 3 properties, Priority #, Description, and Reference #. The program is suppose to allow you to print the Item from Arraylist based on the item's reference #. For some reason the compiler won't let me iterate through the ArrayList to find the matching item.
The part I'm stuck on (inside the method 'findbyrefer'):
for(Object list : list.getMyList()){
if(list.getReference.equals(num)){
System.out.println(list);
}
My main:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myscanner = new Scanner(System.in);
boolean exit = false;
boolean error = false;
boolean error1 = false;
String input = "";
int num = 0;
System.out.println("Welcome to Your To-Do List!\n1 = Create New Item \n2 = Exit \n3 = Display Item \n4 = Delete Item");
while(exit == false){
Item item = new Item();
do{
try {
System.out.println("Enter a command ");
input = myscanner.nextLine();
num = Integer.parseInt(input);
if(num == 1){
item.reference();
System.out.println("Reference: "+ item.getReference() + "\nDescription: " + item.getDescription() + "\nPriority: " + item.getPriority());
error = true;
}
/**
* This creates the item
*/
else if(num == 2){
exit = true;
System.out.println("Bye"); break;
}
else if(num == 3){
item.findbyrefer();
/**
* This is the part I'm stuck at
*/
}
else{
error = true;
System.out.println("invalid");
}
}
catch(Exception e){
System.out.println("invalid input");
error = true;
}
}
while(error);
}
}
My Item Class:
public class Item {
private Scanner myScanner;
private int reference;
private String description;
private int priority;
List list = new List();
public void setReference(int reference) {
this.reference = reference;
}
public int getReference() {
return reference;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
}
public void setPriority(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public void reference(){
boolean error = false;
int x = 0;
do{
try{
System.out.println("Assign this item with a reference number: ");
myScanner = new Scanner(System.in);
x=myScanner.nextInt();
setReference(x);
error=false;
break;
}
catch(Exception e){
error = true;
System.out.println("invalid");
}
} while(error);
description();
}
public void description(){
boolean error = true;
while(error){
try{
System.out.println("Enter the description: ");
myScanner = new Scanner(System.in);
String input = myScanner.nextLine();
setDescription(input);
error=false;
break;
}
catch(Exception e){
error = true;
System.out.println("invalid");
break;
}
}
priority();
}
public void priority(){
boolean error = false;
do{
try{
System.out.println("Assign this item with a priority number: ");
myScanner = new Scanner(System.in);
setPriority(myScanner.nextInt());
error=false;
}
catch(Exception e){
error = true;
System.out.println("invalid");
}
}
while(error==true);
list.addItem(this);
System.out.println(list.getMyList());
}
public void findbyrefer(){
boolean error1 = false;
String input = "";
int num = 0;
do{
try{
System.out.println("Enter the reference number of the item you want to show");
myScanner = new Scanner(System.in);
input = myScanner.nextLine();
num = Integer.parseInt(input);
for(Object list : list.getMyList()){
if(list.equals(num)){
System.out.println(list);
}
else{
System.out.println("not working");
}
}
}
catch(Exception e){
error1 = true;
System.out.println("invalid");
}
}
while(error1 = true);
}
}
My List Class that contains my actual ArrayList:
public class List {
public ArrayList<Object> MyList = new ArrayList<Object>();
public void setMyList(ArrayList<Object> myList) {
this.MyList = myList;
}
public ArrayList<Object> getMyList() {
return MyList;
}
public void addItem (Object t){
getMyList().add(t);
}
There is no getReference method on Object.
Since your ArrayList contains Items, let it know that:
ArrayList<Item> myList = new ArrayList<>();
// ------^^^^^^
Now looking at your loop:
for(Object list : list.getMyList()){
if(list.getReference.equals(num)){
System.out.println(list);
}
}
We need to:
Change Object to Item
Use a different identifier than list for the items (just to avoid confusion)
Call getReference (add ())
Use ==, not equals, to check num (equals is for objects)
So:
for (Item item : list.getMyList()) {
if (item.getReference() == num){
System.out.println(item);
}
}
Add () parenthesis for getReference method of list and use (==) equal operator.
for(Object list : list.getMyList()){
if(list.getReference() == num)){
System.out.println(list);
}
}

want to add searchBook udpateBook deleteBook in linked list in java

package pro;
import java.util.Scanner;
public class bookapp {
static book head, pointer;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to SZABIST BOOK STORE");
int choice = 0;
do {
System.out.println();
System.out.println("1. INSERT BOOK");
System.out.println("2. DELETE BOOK");
System.out.println("3. UDPATE BOOK");
System.out.println("4. SEARCH BOOK");
System.out.println("5. VIEW BOOK(S)");
System.out.println("6. EXIT");
System.out.print("Enter Choice: ");
try {
choice = Integer.parseInt(input.nextLine());
} catch (Exception e) {
e.printStackTrace();
}
switch (choice) {
case 1:
addBook();
break;
case 2:
deleteBook();
break;
case 3:
udpateBook();
break;
case 4:
searchBook();
break;
case 5:
viewBook();
break;
case 6:
input.close();
System.exit(0);
break;
default:
System.out.println("Wrong Choice TRY AGAIN!");
}
} while (true);
}
private static void viewBook() {
if (head == null) {
System.out.println("List is EMPTY !");
} else {
pointer = head;
for (book i = pointer; i != null; i = pointer.next) {
System.out.println(pointer.getBook());
pointer = pointer.next;
}
}
}
private static void searchBook() {
// TODO Auto-generated method stub
}
private static void udpateBook() {
// TODO Auto-generated method stub
}
private static void deleteBook() {
// TODO Auto-generated method stub
}
public static void addBook() {
if (head == null) {
String details[] = enterDetails();
pointer = new book(details[0], details[1], details[2]);
head = pointer;
pointer.next = null;
} else {
String details[] = enterDetails();
pointer.next = new book(details[0], details[1], details[2]);
pointer = pointer.next;
pointer.next = null;
}
}
public static String[] enterDetails() {
String[] details = new String[3];
try {
String title;
String ISBN;
System.out.print("Please enter Book Title: ");
title = input.nextLine();
System.out.print("Please enter Book ISBN: ");
ISBN = input.nextLine();
String authors;
System.out.print("Enter Book author(s): ");
authors = input.nextLine();
details[0] = title;
details[1] = ISBN;
details[2] = authors;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return details;
}
}
//class
package pro;
public class book {
String[] authors;
static String publisher;
final String ISBN;
final String title;
book next;
book(String title, String ISBN, String... authors){
this.ISBN = ISBN;
this.title = title;
this.authors = new String[authors.length];
int i=0;
for (String s: authors){
this.authors[i]=s;
i++;
}
}
public String getBook(){
return "BOOK TITLE: " + this.title + "\n" + "BOOK ISBN: " + this.ISBN +
"\n" + "BOOK AUTHOR(S):" + getAuthors() +"\n"
;
}
public String getAuthors(){
StringBuilder s = new StringBuilder();
for (String s1: this.authors){
s.append(s1 + ",");
}
return s.toString();
}
}
want to add search Book update book delete Book in linked list in java
when i press 2 it update book
when i press 3 it search Book
when i press 4 it delete book
In linked list in java.
cant find the way out
Call this with the book id to search from your search method.
private static void Book searchBook(int book_id) {
if(head == null)
return null;
Book iterator = head;
while(iterator != null){
if(iterator.getId() == book_id){
return iterator;
}
iterator = iterator.next;
}
return null;
}

Categories