Java blackjack program - java

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.

Related

Having issues with code, How can I reinitialize my player

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

Battleship game in java

I need help with a program I have to finish by this Saturday, it is really important, I actually have this code in spanish though. I am looking for a way to make a simple IA, here are my classes:
public class Game {
private HumanPlayer[] players;
public Game() {
this.players = new HumanPlayer[]{
new HumanPlayer(1),
new HumanPlayer(2)
};
}
public void start() {
int i = 0;
int j = 1;
int len = players.length;
HumanPlayer player = null;
this.players[i].colocaBarcos();
this.players[j].colocaBarcos2();
while(players[0].getVidasRestantes() > 0 &&
players[1].getVidasRestantes() > 0) {
players[i++ % len].dispararA(players[j++ % len]);
player = (players[0].getVidasRestantes() < players[1].getVidasRestantes()) ?
players[1] :
players[0];
}
System.out.printf("Enhorabuena Player %d, ganaste!",player.getId());
}
}
public class AguaField implements IGameField {
private boolean fieldGolpeado = false;
#Override
public char getIcon() {
return fieldGolpeado ? 'M' : '~';
}
#Override
public Resultado dispararA() {
fieldGolpeado = true;
return Resultado.NO_GOLPE;
}
}
public class Barco {
private final String nombre;
private final int tamaño;
private int vidas;
public Barco(String nombre, int tamaño) {
this.nombre = nombre;
this.tamaño = tamaño;
this.vidas = tamaño;
}
public void golpear() {
if(vidas > 0) {
System.out.printf("%nBuen golpe! El %s fue golpeado", nombre);
vidas--;
}
else {
System.out.println("El barco fue destruido");
}
}
public Resultado getEstado() {
if(vidas == 0) {
return Resultado.DESTRUIDO;
}
else if(vidas < tamaño) {
return Resultado.PARCIAL_GOLPE;
}
else {
return Resultado.NO_GOLPE;
}
}
public String getNombre() {
return nombre;
}
public int getTamaño() {
return tamaño;
}
}
public class BarcoField implements IGameField {
private final Barco ship;
public BarcoField(Barco ship) {
this.ship = ship;
}
#Override
public char getIcon() {
char icon;
Resultado barcoEstado = ship.getEstado();
switch (barcoEstado) {
case PARCIAL_GOLPE: icon = 'O';
break;
case DESTRUIDO: icon = 'O';
break;
case NO_GOLPE: icon = 'X';
break;
default: icon = ' ';
break;
}
return icon;
}
#Override
public Resultado dispararA() {
ship.golpear();
return ship.getEstado();
}
}
public class BarcoTamaño {
private BarcoTamaño() {
}
public static final int CARRIER = 6;
public static final int BATTLESHIP = 4;
public static final int CRUISER = 2;
public static final int DESTROYER = 1;
}
public class HumanPlayer implements IPlayer {
private int totalVidas = 17;
private int id;
private Tablero tablero;
private Tablero tablero2;
private Scanner scanner;
public HumanPlayer(int id) {
this.id = id;
this.tablero = new Tablero();
this.scanner = new Scanner(System.in);
}
public int getId() {
return id;
}
public Tablero getTablero() {
return tablero;
}
#Override
public void colocaBarcos() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero();
}
public void colocaBarcos2() {
System.out.printf("%n======== Player %d - Coloca tus barcos ========%n", id);
tablero.colocaBarcosTablero2();
}
#Override
public void dispararA(IPlayer opponent) {
System.out.printf("%n Bien player %d - Introduce las coordenadas de tu ataque: ", id);
boolean esPuntoValido = false;
while(!esPuntoValido) {
try {
Point point = new Point(scanner.nextInt(), scanner.nextInt());
int x = (int)point.getX() - 1;
int y = (int)point.getY() - 1;
Resultado resultado = ((HumanPlayer)opponent)
.getTablero()
.getField(x, y)
.dispararA();
if(resultado == Resultado.PARCIAL_GOLPE || resultado == Resultado.DESTRUIDO) {
totalVidas--;
}
esPuntoValido = true;
}
catch(IllegalArgumentException e) {
System.out.printf(e.getMessage());
}
}
}
#Override
public int getVidasRestantes() {
return totalVidas;
}
}
public interface IGameField {
char getIcon();
Resultado dispararA();
}
public interface IPlayer {
void colocaBarcos();
void dispararA(IPlayer opponent);
int getVidasRestantes();
}
public enum Resultado {
NO_GOLPE,
PARCIAL_GOLPE,
DESTRUIDO
}
public class Tablero {
private static final char AGUA = '~';
private static final int TABLERO_SIZE = 10;
private static final char[] TABLERO_LETRAS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
private static final String HORIZONTAL = "H";
private static final String VERTICAL = "V";
private static final String HORIZONTAL2 = "h";
private static final String VERTICAL2 = "v";
private Scanner scanner;
private IGameField[][] tablero;
private static final Barco[] barcos;
static {
barcos = new Barco[]{
new Barco("Carrier", BarcoTamaño.CARRIER),
new Barco("Battleship1", BarcoTamaño.BATTLESHIP),
new Barco("Battleship2", BarcoTamaño.BATTLESHIP),
new Barco("Cruiser1", BarcoTamaño.CRUISER),
new Barco("Cruiser2", BarcoTamaño.CRUISER),
new Barco("Cruiser3", BarcoTamaño.CRUISER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER),
new Barco("Destroyer", BarcoTamaño.DESTROYER)
};
}
public void escogerBarco(){
System.out.println("Que barco quieres introducir? ");
String barcoEscogido = scanner.nextLine();
if (barcoEscogido == "Carrier"){
new Barco("Carrier", BarcoTamaño.CARRIER);
}
}
public Tablero() {
this.scanner = new Scanner(System.in);
this.tablero = new IGameField[TABLERO_SIZE][TABLERO_SIZE];
for(int i = 0; i < TABLERO_SIZE; i++) {
for(int j = 0; j < TABLERO_SIZE; j++) {
tablero[i][j] = new AguaField();
}
}
}
public void colocaBarcosTablero() {
for(Barco ship : barcos) {
boolean horizontal = preguntaDireccionValida();
Point puntoInicio = preguntaPuntoInicio(ship, horizontal);
colocaBarcoValido(ship, puntoInicio, horizontal);
printTablero();
}
}
public void colocaBarcosTablero2() {
for(Barco ship2 : barcos) {
boolean horizontal2 = preguntaDireccionValida2();
Point puntoInicio2 = preguntaPuntoInicio2(ship2, horizontal2);
colocaBarcoValido(ship2, puntoInicio2, horizontal2);
printTablero();
}
}
public IGameField getField(int x, int y) {
if(!dentroTablero(x, y)) {
throw new IllegalArgumentException("Fuera del trablero - intenta de nuevo: ");
}
return tablero[y][x];
}
public void printTablero() {
System.out.print("\t");
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print(TABLERO_LETRAS[i] + "\t");
}
System.out.println();
for(int i = 0; i < TABLERO_SIZE; i++) {
System.out.print((i+1) + "\t");
for(int j = 0; j < TABLERO_SIZE; j++) {
System.out.print(tablero[i][j].getIcon() + "\t");
}
System.out.println();
}
}
private boolean preguntaDireccionValida() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion;
do {
direccion = scanner.nextLine().trim();
}while (!HORIZONTAL.equals(direccion) && !VERTICAL.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private boolean preguntaDireccionValida2() {
System.out.printf("%nQuieres introducir el barco horizontalmente (H) o verticalmente (V)?");
String direccion = "HV";
Random aleatorio = new Random();
do {
direccion.charAt(aleatorio.nextInt(direccion.length()));
}while (!HORIZONTAL2.equals(direccion) && !VERTICAL2.equals(direccion));
return HORIZONTAL.equals(direccion);
}
private Point preguntaPuntoInicio(Barco ship, boolean horizontal) {
Point from;
do{
System.out.printf("%nIntroduce la posicion de %s (tamaño %d): ", ship.getNombre(), ship.getTamaño());
from = new Point(scanner.nextInt(), scanner.nextInt());
}while(!esPuntoInicioValido(from, ship.getTamaño(), horizontal));
return from;
}
private Point preguntaPuntoInicio2(Barco ship, boolean horizontal) {
Random random2 = new Random();
Point from2;
do{
from2 = new Point(random2.nextInt(10), random2.nextInt(10));
}while(!esPuntoInicioValido(from2, ship.getTamaño(), horizontal));
return from2;
}
private boolean esPuntoInicioValido(Point from, int longitud, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
int x = (int)from.getX() - 1;
int y = (int)from.getY() - 1;
if(!dentroTablero(x, y) || (!dentroTablero(x + longitud,y) && horizontal) || (!dentroTablero(x, y + longitud) && !horizontal)){
return false;
}
for(int i = 0; i < longitud; i++) {
if(tablero[(int)from.getY() + i *yDiff - 1]
[(int)from.getX() + i *xDiff - 1].getIcon() != AGUA){
return false;
}
}
return true;
}
private boolean dentroTablero(int x, int y){
return x <= TABLERO_SIZE && x >= 0 && y <= TABLERO_SIZE && y >= 0;}
private void colocaBarcoValido(Barco ship, Point puntoInicio, boolean horizontal) {
int xDiff = 0;
int yDiff = 0;
if(horizontal) {
xDiff = 1;
}
else {
yDiff = 1;
}
for(int i = 0; i < ship.getTamaño() ; i++) {
tablero[(int)puntoInicio.getY() + i*yDiff - 1]
[(int)puntoInicio.getX()+ i*xDiff - 1] = new BarcoField(ship);
}
}
}
The thing is that I got stuck and I don't know how to continue. Sorry for my bad English and if I placed this wrong, it is my first time using stackoverflow!

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

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.lang.NullPointerException when object is instantiated?

So I'm fairly certain that this code should work, but when I run it it spits out that.
Problem occurs at:
return planetArray[arr[0].viewPosition()].testCost();
My code is posted below. I've scoured over this but cannot see how it's null?
The purpose is to take the currentPosition of the Player[x] and use it to check the cost of the planet Player[x] is on and return the cost.
Sorry if I posted too much / not enough code, wasn't sure where the error was.
public class Launcher
{
private static Planet returnCost;
private static Planet myTest;
private static PlanetInfo myPlanetInfo;
private static PlanetInfo[] planetArray;
private static Player[] arr; //NEED THIS FOR arr = myArray.getPlayerArray(); to work..
public static void main(String[] args)
{
Planet myPlanetArray = new Planet();
PlayerArray myArray = new PlayerArray();
myPlanetArray.getPlanetArray();
myArray.getPlayerArray();
planetArray = myPlanetArray.getPlanetArray();
arr = myArray.getPlayerArray(); //holy moses this worked...
System.out.println("player 1's ID: " + arr[0].viewID());
System.out.println("player 1's balance: " + arr[0].viewBalance());
arr[0].playerGo();
System.out.println("You've landed on: " /* + myPlanetArray.returnName()*/ + " it costs: " + myPlanetArray.returnCost());/*arr[0].viewPosition());*/
//^^^this line causes the error
}
}
and...
public class PlanetInfo
{
Scanner scan = new Scanner(System.in);
private static PlanetInfo[] planetArray;
private static Player[] arr;
private String name; //same with this
private int cost; // doesnt need setter or getter methods, it's permanent.
private int position; // same with this
private int group; // same with this
private int owner;
private int rent; // done
private int town;
private int city;
private int sellValue; // same with this
public void setRent()
{
System.out.println("How many towns would you like to add?");
town = scan.nextInt();
if(position != 39 && town == 1) {rent *= 5;}
else if(position == 39 && town == 1){rent = 200;}
if(town == 2) {rent *= 3;}
if(position <= 13 && town == 3) {rent *= 3;}
else if(position > 13 && town == 3) {rent *= 2.5;}
if(position < 20 && town == 4) {rent *= 1.45;}
else if((position > 20 && position < 40) && town == 4) {rent *= 1.3;}
}
public int getRent(){return rent;}
//public void setOwner(){owner = arr[0].viewID();}
//public int getOwner(){return owner;}
//^^^^Will do this in Player class.
public PlanetInfo(String planetName, int planetCost, int boardPosition, int groupColor, int currentOwner, int startRent, int numTown, int numcity)
{
cost = planetCost;
name = planetName;
position = boardPosition;
group = groupColor;
owner = currentOwner;
rent = startRent;
town = numTown;
city = numcity;
sellValue = cost/2;
}
}
finally..
import java.util.Scanner;
import java.util.Random;
public class Planet
{
private static Player[] arr;
private static PlanetInfo[] planetArray;
private String name;
private int cost;
private int playerPosition;
public void Planet()
{
//cost,boardposition,color,currentowner,startingRent,#towns,#city
Planet testPlanet = new Planet();
PlayerArray myArray = new PlayerArray();
PlanetInfo[] planetArray;
myArray.getPlayerArray();
arr = myArray.getPlayerArray();
planetArray = new PlanetInfo[40];
planetArray[1] = new PlanetInfo("Tatooine Mos Eisley",60,1,1,-1,2,0,0);
planetArray[3] = new PlanetInfo("Tatooine Mos Espa",60,3,1,0,-1,0,0);
planetArray[6] = new PlanetInfo("Dagobah",100,6,2,-1,6,0,0);
//MORE OF THIS NOT IMPORTANT SO REMOVED
planetArray[34] = new PlanetInfo("Alderaan",320,34,7,-1,28,0,0);
planetArray[37] = new PlanetInfo("Coruscant Jedi Temple",350,37,8,-1,35,0,0);
planetArray[39] = new PlanetInfo("Coruscant Senate",400,39,8,-1,50,0,0);
public int testCost()
{
return cost;
}
}
public PlanetInfo[] getPlanetArray()
{
return planetArray;
}
public String testName()
{
return name;
}
public int testCost()
{
return cost;
}
public int returnCost() //returns int of cost
{
return planetArray[arr[0].viewPosition()].testCost();
}
}
You never show what the PlanetArray class looks like. Most likely you are not instantiating the Player[] array that gets returned in the getPlanetArray() method.

Categories