Eclipse Java Compiler Errors - java

What does the following error messages mean?
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token "void", # expected
Syntax error on token "]", :: expected after this token
Syntax error, insert "enum Identifier" to complete EnumHeader
The line it does not like is:
public static void main(String[] args) {
My full WIP code in case you need to see it for context is as follows. Eclipse automatically sets in that line and I have never had issues with it before.
public class Card {
public class cardValue()
public static int suit;
public static int faceValue;
{
static int getfaceValue()
{
return faceValue;
}
setfaceValue(String faceValue)
{
cardFaceValue = faceValue;
return faceValue;
}
static int getSuit()
{
return suit;
}
setSuit(int suit)
{
cardSuit = suit;
return suit;
}
}
public static void main(String[] args) {
cardValue card1 = new cardValue();
// Suit values into strings for Hearts,Spades,Clubs, Diamonds
if (cardValue.getSuit() == 1)
{
System.out.print(" of Hearts");
}
if (cardValue.getSuit() == 2)
{
System.out.print(" of Spades");
}
if (cardValue.getSuit() == 3)
{
System.out.print(" of Clubs");
}
if (cardValue.getSuit() == 4)
{
System.out.print(" of Diamonds");
}
System.out.println(card1.getSuit());
}
}

I really recommend searching around and learning about classes and objects in Java.
But if I get what you're trying to do, this will just work:
public class Card {
private int suit;
private int faceValue;
public Card (int suit, int faceValue) {
setSuit(suit);
setFaceValue(faceValue);
}
int getFaceValue () {
return faceValue;
}
void setFaceValue (int faceValue) {
this.faceValue = faceValue;
}
int getSuit () {
return suit;
}
void setSuit (int suit) {
this.suit = suit;
}
public static void main (String[] args) {
Card card = new Card(1, 4);
System.out.print(card.getFaceValue());
// Suit values into strings for Hearts,Spades,Clubs, Diamonds
if (card.getSuit() == 1) {
System.out.println(" of Hearts");
} else if (card.getSuit() == 2) {
System.out.println(" of Spades");
} else if (card.getSuit() == 3) {
System.out.println(" of Clubs");
} else if (card.getSuit() == 4) {
System.out.println(" of Diamonds");
}
}
}

IF you have imports inside class declaration, need to come before your class declaration.
import java.io.*;
import java.util.*;
or similar
Check your indentation, which is incorrect. You may have {} out of balance.
class Card {
private int suit;
private int faceValue;
public Card (int suit, int faceValue)
{
setSuit(suit);
setfaceValue(faceValue);
}
int getfaceValue () {
return faceValue;
}
void setfaceValue (int faceValue) {
this.faceValue = faceValue;
}
int getSuit () {
return suit;
}
void setSuit (int suit) {
this.suit = suit;
}
public static void main (String[] args) {
Card card = new Card(1, 4);
System.out.print(card.getfaceValue());
// Suit values into strings for Hearts,Spades,Clubs, Diamonds
if (card.getSuit() == 1) {
System.out.println(" of Hearts");
} else if (card.getSuit() == 2) {
System.out.println(" of Spades");
} else if (card.getSuit() == 3) {
System.out.println(" of Clubs");
} else if (card.getSuit() == 4) {
System.out.println(" of Diamonds");
}
}
}

Related

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

How do i generate a deck of cards in Java?

I have tried again and again but the loop is stuck at the king of clubs.
currently I am trying to generate a deck of cards and print it out to check if the deck is actual
import java.util.*;
import java.math.*;
public class Deck extends Card{
private static Card[][]cardDeck=new Card[4][13];
int counter;
public Deck (String suit, String cardType, int value)
{
super(suit,cardType,value);
}
public void removeCard()
{
if(counter>=40)
generateDeck();
int Randr=(int)(Math.random()*26);
int Randc=(int)(Math.random()*2);
if(cardDeck[Randr][Randc]==null)
{
removeCard();
}
else
{
cardDeck[Randr][Randc]=null;
counter++;
}
}
public void print2DArray()
{
for(int i=0;i<cardDeck.length;i++)
{
for(int j=0;j<cardDeck[0].length;j++)
{
System.out.print(super.draw(cardDeck[i][j])+" "+j);
}
System.out.println();
}
}
public static void generateDeck()
{
for(int i=0; i<cardDeck.length;i++) {
for(int j=0;j<cardDeck[0].length;j++) {
if(i==0)
{
if(j==0)
{
cardDeck[0][0]=new Card("Clubs","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Clubs",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Clubs","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Clubs","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Clubs","King",10);
continue;
}
else if(i==1)
{
if(j==0)
{
cardDeck[1][0]=new Card("Hearts","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Hearts",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Hearts","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Hearts","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Hearts","King",10);
continue;
}
}
else if(i==2)
{
if(j==0)
{
cardDeck[2][0]=new Card("Spades","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Spades",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Spades","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Spades","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Spades","King",10);
continue;
}
}
else if(i==3)
{
if(j==0)
{
cardDeck[3][0]=new Card("Diamonds","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Diamonds",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Diamonds","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Diamonds","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Diamonds","King",10);
continue;
}
}
}
}
}
}
}
my card class is just a basic class with a few get methods
public class Card {
private static String suit;
private static int numVal;
private static String cardType;
public Card(String s,String cT, int val) {
suit=s;
numVal=val;
cardType=cT;
}
public String draw(Card card) {
return "Your card is "+card.getSuit()+" "+card.getCardType()+" its value is "+card.getValue();
}
public static String getSuit()
{
return suit;
}
public static String getCardType()
{
return cardType;
}
public static int getValue()
{
return numVal;
}
}
my main method is just to check if it will print
public class TestEnvironment {
public static void main(String[] args) {
Deck x= new Deck("","",0);
x.generateDeck();
x.print2DArray();
}
}
heres my updated code for the if else statements aforementioned
import java.util.*;
import java.math.*;
public class Deck extends Card{
private static Card[][]cardDeck=new Card[4][13];
int counter;
public Deck (String suit, String cardType, int value)
{
super(suit,cardType,value);
}
public void removeCard()
{
if(counter>=40)
generateDeck();
int Randr=(int)(Math.random()*26);
int Randc=(int)(Math.random()*2);
if(cardDeck[Randr][Randc]==null)
{
removeCard();
}
else
{
cardDeck[Randr][Randc]=null;
counter++;
}
}
public void print2DArray()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<cardDeck[0].length;j++)
{
System.out.print(i);
//System.out.println(super.draw(cardDeck[i][j])+" "+i+","+j);
}
System.out.println();
}
}
public static void generateDeck()
{ int value=0;
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
for (int i=0;i<suits.length;i++)
for (int j=0;j<ranks.length;j++)
{
cardDeck[i][j] = new Card(suits[i],ranks[j],value);
if(j>9)
value =10;
else
value=j+1;
cardDeck[i][j] = new Card(suits[i],ranks[j],value);
}
Don't use a 2D Array. Instead use an ArrayList to hold the cards.
Then you create two loops to add the cards to the ArrayList. The outer loop will iterate through the 4 suits and the inner loop will add the 13 cards for each suit.
Then you can use Collections.shuffle() to shuffle the Cards in the ArrayList.
To play a card you just remove card 0 from the ArrayList.
Edit:
but the loop is stuck at the king of clubs.
Well your generateCards() method uses too many if/else statements to generate the cards. It is hard to notice which if/else statement might be causing the problem.
You can simplify the code by using arrays and loops.
Something like:
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace", "2", "3", ... , "Jack", "Queen", "King"};
for (each suit) // assume i is the index
for (each rank) // assume j is the index
{
int value = (j < 10) ? 10 : j;
cardDeck[i][j] = new Card(...);
}
}
Edit 2:
it is stuck at the spades of kings
I'm guessing the following is your problem:
private static String suit;
private static int numVal;
private static String cardType;
Don't use static variables. The Static keyword means that all instances of the Card class will share the same value.

Sorting Card objects inside of the Hand object

I have almost everything ready for my poker game. What I want to do next is to sort cards in players hand by rank value. You know "two" is byte 2, "three" is byte 3 etc...
This is my enum CardRank class
public enum CardRank {
TWO((byte)2, "Two"),
THREE((byte)3, "Three"),
FOUR((byte)4, "Four"),
FIVE((byte)5, "Five"),
SIX((byte)6, "Six"),
SEVEN((byte)7, "Seven"),
EIGHT((byte)8, "Eight"),
NINE((byte)9, "Nine"),
TEN((byte)10, "Ten"),
JACK((byte)11, "Jack"),
QUEEN((byte)12, "Queen"),
KING((byte)13, "King"),
ACE((byte)14, "Ace");
private final byte rankValue;
private final String rankValueName;
//Constructor
private CardRank(byte rankValue, String rankValueName){
this.rankValue=rankValue;
this.rankValueName = rankValueName;
}
//reusable methods
protected byte getRankValue(){
return rankValue;
}
protected String getRankValueName(){
return rankValueName;
}
}
I need to find a way to sort them using enum values but to be honest I don't really know how.
This method returns enum values of player hand cards:
protected void sortHand(){
for (Hand playerHand: players){
i = 0;
while(i<5){
System.out.println(playerHand.cards.get(i).getRankValue());
i++;
}
}
}
I can't use Collections from a very obvious reason:
The method sort(List) in the type Collections is not applicable for the arguments (Hand)
And this is my Hand class
import java.util.ArrayList;
public class Hand {
protected ArrayList<Card> cards;
private String handCards;
// Constructor
protected Hand() {
cards = new ArrayList<Card>(5);
}
// reusable methods
protected void add(Card card) {
cards.add(card);
}
protected void emptyHand() {
cards.clear();
}
protected void flipHandCards() {
for (Card card : cards) {
card.flipCard();
}
}
protected String displayHand() {
handCards = "";
for (Card i : cards) {
handCards += i.toString() + "\n";
}
return handCards;
}
protected boolean giveCard(Card card, Hand differentHand) {
if (!cards.contains(card)) {
return false;
} else {
cards.remove(card);
differentHand.add(card);
return true;
}
}
}
And this is my Card class
public class Card {
private CardSuit suit;
private CardRank rank;
private String cardName;
private boolean visibility;
//Constructor
protected Card(CardRank rank, CardSuit suit){
this.rank = rank;
this.suit = suit;
}
//reusable methods
protected String getCardSuit(){
return suit.getCardSuit();
}
protected byte getRankValue(){
return rank.getRankValue();
}
protected void flipCard(){
visibility = !visibility;
}
public String toString(){
if (visibility){
cardName="";
cardName+=rank.getRankValueName() + " of " + suit.getCardSuit();
}
else{
cardName = "You cannot see your opponents card";
}
return cardName;
}
}
Help. I appreciate for any help that will direct me into the right direction.
Saying you can't use Guava (Google Collections) for this seems incorrect at face value. Just give hand a sort method that lets it interact with cards (which is an ArrayList).
protected void sortHand(){
for (Hand playerHand: players){
List<Card> sortedHand = playerHand.getSortedCards();
// Do whatever
}
}
Hand.java
public class Hand {
...
public List<Card> getSortedCards() {
Collections.sort(cards);
return cards; // Consider deep copying.
}
}
From there, making Card implement Comparable will let you sort the list.
Card.java
public class Card implements Comparable<Card>
{
...
#Override
public int compareTo(Card o) {
if (this.rank.getRankValue() < o.rank.getRankValue()) {
return -1;
}
else if (o.rank.getRankValue() < this.rank.getRankValue()) {
return 1;
}
return 0;
}
}
protected void sortHand(){
for (Hand playerHand: players){
i = 0;
int []arr = new int[5];
while(i<5){
System.out.println(playerHand.cards.get(i).getRankValue());
arr[i] = playerHand.cards.get(i).getRankValue();
i++;
}
Arrays.sort(arr);
}
}
you can try adding it to an array and call Array.sort(). where i assume that getRankvalue will return an int . try this
ArrayLists can be easily sorted using a Comparator.
You would then get something like this:
cards.sort(new Comparator<Card>() {
#Override
public int compare(Card card1, Card card2) {
// return -1 if card1 should come before card2
// return 0 if card1 and card2 have equal values
// return 1 if card1 should come after card2
}
});
I suggest you use a static array to store cards in hand:
public class Hand {
private static final int MAX_CARD = 5;//modify with your value
protected Card[] cards;
private int currentCardNumber;
private String handCards;
// Constructor
protected Hand() {
cards = new Card[MAX_CARD];
currentCardNumber = 0;
}
// reusable methods
protected void add(Card card) {
if (currentCardNumber == MAX_CARD - 1) { return; }
cards[currentCardNumber] = card;
currentCardNumber++;
}
protected void emptyHand() {
for (int i = 0; i < MAX_CARD; i++) {
cards[i] = null;
}
currentCardNumber = 0;
}
protected void flipHandCards() {
for (int i = 0; i < currentCardNumber; i++) {
cards[i].flipCard();
}
}
protected String displayHand() {
handCards = "";
for (int i = 0; i < currentCardNumber; i++) {
handCards += cards[i].toString() + "\n";
}
return handCards;
}
protected boolean giveCard(Card card, Hand differentHand) {
int index = getCardIndex(card);
if (index == -1) {
return false;
} else {
differentHand.add(remove(index));
return true;
}
}
protected void sortHand() {
for(int i = 0; i < currentCardNumber; i++) {
for(int j = i + 1; j < currentCardNumber; j++) {
if(cards[j].getRankValue() < cards[i].getRankValue()) {
Card tmp = cards[j];
cards[j] = cards[i];
cards[i] = tmp;
}
}
}
}
private int getCardIndex(Card card) {
for (int i = 0; i < currentCardNumber; i++) {
if(card.equals(cards[i]) {
return i;
}
}
return -1;
}
private Card remove(int cardIndex) {
if (currentCardNumber == 0) { return null; }
Card tmp = cards[cardIndex];
for (int i = cardIndex + 1; i < currentCardNumber; i++) {
cards[i - 1] = cards[i];
}
cards[currentCardNumber - 1] = null;
currentCardNumber--;
return tmp;
}
}
Or you can create your own List and apply a your own sort method.

Java blackjack program

So I rewrote it with your suggestion (Todd Hopp) and updated the post in the (*) section in the BlackJack class so you can see how I have it now but I'm still getting the same errors and it is not printing the computePlayerValue for some reason....
ERROR:
Exception in thread "main" java.lang.NumberFormatException: For input string: "King" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at BlackJack.dealCards(BlackJack.java:25)
at PlayCardGame.main(PlayCardGame.java:9)
P.S. I'm was trying to look this up in the book but couldn't find the answer...The BlackJack class is partially source code from an earlier chapter in the book and I couldn't figure out if it was necessary to have super(); in the constructor there? I thought it only had to do if the parent class constructor had an argument? Any help on if it has to be there and if so what it's doing.
BlackJack Class
public class BlackJack extends CardGameFP{
int computePlayerValue;
int computeDealerValue;
int cardValue;
public BlackJack() {
**super();**
player1 = 2;
player2 = 2;
}
public void display() {
System.out.println("BlackJack");
}
//*************************************************************
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
public void dealCards() {
//Player 1
System.out.println("Player 1:");
for(int x = 0; x < playerHand; x++) {
shuffle();
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit());
}
cardValue1 = getCardValue(fullDeck[0]);
cardValue2 = getCardValue(fullDeck[1]);
computePlayerValue = cardValue1 + cardValue2;
System.out.println(computePlayerValue);
}
//*************************************************************
//Dealer hand
System.out.println("\nPlayer 2:");
for(int x = 0; x < player2; x++) {
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit() );
shuffle();
}
}
}
public class Card {
protected String suit;
protected int value;
protected String rank;
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
public String getRank() {
return rank;
}
public int getValue() {
return value;
}
public String getSuit() {
return suit;
}
public void setSuit(String st) {
suit = st;
}
public void setValue(int val) {
if(val >= LOW_VALUE && val <= HIGH_VALUE) {
value = val;
}
else {
value = LOW_VALUE;
}
if(val == 1) {
rank = "Ace";
}
else if(val == 11) {
rank = "Jack";
}
else if(val == 12) {
rank = "Queen";
}
else if(val == 13) {
rank = "King";
}
else {
rank = Integer.toString(value);
}
}
}
CardGame Class
abstract public class CardGameFP {
int suitNum = 1;
int val = 1;
int player1;
int player2;
protected final int DECK_OF_CARDS = 52;
Card fullDeck[] = new Card[DECK_OF_CARDS];
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
protected final int HIGH_SUIT = 4;
protected final int CARDS_IN_SUIT = 13;
public abstract void display();
public abstract void dealCards();
public CardGameFP() {
for(int i = 0; i < fullDeck.length; i++) {
fullDeck[i] = new Card();
if(suitNum == 1) {
fullDeck[i].setSuit("Spades");
}
else if(suitNum == 2) {
fullDeck[i].setSuit("Hearts");
}
else if(suitNum == 3) {
fullDeck[i].setSuit("Diamonds");
}
else {
fullDeck[i].setSuit("Clubs");
}
fullDeck[i].setValue(val);
val++;
if(val > HIGH_VALUE) {
suitNum++;
val = 1;
}
}//end for
}
public void shuffle() {
for(int firstCard = 0; firstCard < DECK_OF_CARDS; firstCard++ ) {
firstCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
int secondCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
Card temp = fullDeck[firstCard];
fullDeck[firstCard] = fullDeck[secondCard];
fullDeck[secondCard] = temp;
}
}
}
PlayCardGame Class
PlayerCardGame
public class PlayCardGame {
public static void main(String[] args) {
Card CG = new Card();
BlackJack BJ = new BlackJack();
BJ.display();
BJ.dealCards();
}
}
Instead of this line:
cardValue = Integer.parseInt(fullDeck[0].getRank());
I suggest that you create a getCardValue(Card) method:
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
and then use:
cardValue = getCardValue(fullDeck[0]);
EDIT: Following the suggestion by #WorldSEnder, you can define a Rank enum:
public enum Rank {
ACE("Ace", 1),
TWO("2", 2),
...
QUEEN("Queen", 10),
KING("King", 10);
private final String displayName;
private final int value;
protected Rank(String displayName, int value) {
this.displayName = displayName;
this.value = value;
}
public String displayName() {
return displayName;
}
public int value() {
return value;
}
}
Then you can modify Card to use a Rank instead of a String for the rank and use:
cardValue = fullDeck[0].getRank().value();
When you call :
cardValue = Integer.parseInt(fullDeck[0].getRank());
the method Interger.parseInt() is attempting to read an int from a string. The problem is that some cards have ranks which themselves are not strings like, King. So when you return the rank of that card, parseInt() doesn't know how to handle King. You should instead be getting the cards actual value using fullDeck[0].getVaule() and parsing that instead. It will be a string between 1 and 13.

Categories