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.
Related
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
I'm working on a program which should instantiate n amount of threads. Their job is to draw from a deck existing of 52 distinct cards, wait until the round have been evaluated(who had the highest card) and the user has the highest card shown and then repeat until the deck is empty.
The first round runs flawless, not accounting for the wrong evaluation of the cards, but then the program just locks. Never drawing new cards.
I can't quite figure out what the problem is, but my guess is that I'm calling notifyAll() before the threads wake, causing a deadlock. Even though I'm counting the number of waiting threads and only notifying if the number of waiting threads corresponds to the number of players.
EDIT: I found out that if I debug, the code runs smoothly and as intended. But as soon as I run it, it runs as earlier described.
public class Deck {
Stack<Card> stack = new Stack<>();
public Deck()
{
makeAndShuffleDeck();
}
public synchronized Card drawOneCard()
{
Card card = stack.pop();
System.out.println(Thread.currentThread() + " is drawing " + card);
return card;
}
public void setCardValues(int x)
{
if(x == 0)
{
Rank.ACE.setValue(14);
}
else
{
Rank.ACE.setValue(1);
}
}
public void makeAndShuffleDeck()
{
for(Suit suit : Suit.values())
{
for(Rank value : Rank.values())
{
stack.add(new Card(suit,value));
}
}
Collections.shuffle(stack);
}
public Stack<Card> getDeck()
{
return stack;
}
}
public class Round {
ArrayList<Thread> playersInTheRound = new ArrayList<>();
ArrayList<Card> cardsDrawnInTheRound = new ArrayList<>();
Deck deck;
int numberOfRounds;
public Round(int nrOfPlayers, Deck deck)
{
this.deck = deck;
fillListWithPlayers(nrOfPlayers);
calcNumberOfRounds();
for(Thread p: playersInTheRound)
{
p.start();
}
}
public void fillListWithPlayers(int nrOfPlayers)
{
for (int i = 0; i < nrOfPlayers; i++)
{
playersInTheRound.add(new Thread(new Player(deck, this)));
}
}
public void addPlayerCards(Card card)
{
cardsDrawnInTheRound.add(card);
}
public void calcNumberOfRounds()
{
numberOfRounds = deck.getDeck().size()/playersInTheRound.size();
}
public void playRound()
{
while(numberOfRounds > 0)
{
findWinnerOfRound();
cardsDrawnInTheRound.clear();
while(Player.waiting == playersInTheRound.size())
{
synchronized (this)
{
this.notifyAll();
}
Player.waiting = 0;
}
numberOfRounds--;
}
}
public void findWinnerOfRound()
{
Card highestCard = null;
Comparator<Card> comp = (Card c1, Card c2) ->
{
if (c1.rank.getValue() == c2.rank.getValue())
{
if (c1.suit.getRank() > c2.suit.getRank())
{
return 1;
}
return -1;
}
if (c1.rank.getValue() > c2.rank.getValue())
{
return 1;
}
return -1;
};
for (int i = 0; i < cardsDrawnInTheRound.size()-1; i++)
{
for (int j = i+1; j < cardsDrawnInTheRound.size(); j++)
{
if(comp.compare(cardsDrawnInTheRound.get(i), cardsDrawnInTheRound.get(j)) == -1)
{
highestCard = cardsDrawnInTheRound.get(j);
}
highestCard = cardsDrawnInTheRound.get(i);
}
}
System.out.println(cardsDrawnInTheRound);
System.out.println("Winner: " + highestCard);
}
}
public class Player implements Runnable {
Deck deck;
Round round;
public static int waiting = 0;
public Player(Deck deck, Round round)
{
this.deck = deck;
this.round = round;
}
#Override
public void run()
{
Card card = deck.drawOneCard();
synchronized (round)
{
try
{
round.addPlayerCards(card);
waiting++;
round.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
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");
}
}
}
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.
What I am trying to do is solving the 8 queen problem to produce 1 solution. I am trying to do this using BFS. Below is what I have done so far. I think all my functions/methods are all correct apart from the final method() which I can't get to work. If I compile and run the following code, I get a NullPointerException. Wondering how I can overcome this problem and get it to work.
public class Queens
{
//Number of rows or columns
public int[][] board; // creating a two dimentional array
public int Queen = 1;
//Indicate an empty square
public boolean Conflict(int row, int col)
{
int[ ][ ]board = new int[8][8];
int row1;
int col1;
boolean flg = false;
row1 = row;
col1 = col;
// check right
while(row1<8)
{
if(board[row1][col1]==1)
{
row1++;
}
}
//check left
while(row1>=0)
{
if(board[row1][col1]==1)
{
row1--;
}
}
// check down
while(col1<8)
{
if(board[row1][col1]==1)
{
col1++;
}
}
// check up
while(col1>1)
{
if (board[row1][col1]==1)
{
col1--;
}
}
//dia-down-right
while(row1<8 && col1<8){
if(board[row1][col1]==1)
{
row1++;
col1++;
}
}
//dia-down-left
while(row1>=0 && col1<8){
if(board[row1][col1]==1)
row1--;
col1++;
}
//dia-up-left
while(row1>=0 && col1>=0){
if(board[row1][col1]==1)
row1--;
col1--;
}
//dia-up-right
while(row1<8 && col1>=0){
if(board[row1][col1]==1)
row1++;
col1--;
}
return flg;
}
public void disp()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
System.out.println(board[j][i]);
}
//System.out.println(board[j][i]);
}
}
public void init()
{
int i,j;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
board[i][j] = 0;
}
}
}
public void placeQueen(int x,int y)
{
board[x][y]= Queen;
Queen++;
}
public void method()
{
int x,y;
int initx=0;
int inity=0;
Queen=0;
init();
placeQueen(initx,inity);
y=0;
while(y<8)
{
x=0;
while(x<8)
{
if(!Conflict(x,y))
{
placeQueen(x,y);
x++;
}
}
y++;
}
if(Queen<8){
if(initx+1<8)
{
initx++;
disp();
}
else
{
initx=0;
if(inity+1<8)
{
inity++;
}
else{
disp();
}
}
}
}
public static void main(String[] args)
{
Queens Main = new Queens();
Main.method();
}
}
You need to initialize the board on line 5, otherwise when called in init board:
board[i][j] = 0;
board[i][j] is null
public class Queens
{
//Number of rows or columns
public int[][] board = new int[8][8]; // creating a two dimentional array
public int Queen = 1;