Any advice on how to fix this Stack Overflow error? Java - java

While developing a simple auto generating game of war in my free time, I ran into a "StackOverFlow" error.
Here is my Deck class where the error occurs:
It occurs in my compare() method. Any insight as to what I can do to avoid this error is accepted as I am struggling to understand what can be done to fix this and have little knowledge as to what this error even means besides my class doesn't have recursion done well. Thanks!
import java.util.*;
import java.math.*;
public class Deck
{
private int num = 0;
private int cardnum2 = 0;
private int cardnum = 0;
private int decrease = 0;
private int rnd = 0;
private int winner = 0;
private String suit = " ";
private int suitNum = 0;
private int val = 1;
private String name = "";
private ArrayList<Card> Deck = new ArrayList<Card>();
private Card[] cardCheck = new Card[51];
private ArrayList<Card> play1 = new ArrayList<Card>();
private ArrayList<Card> play2 = new ArrayList<Card>();
public Deck()
{
createDeck();
}
public void createDeck()
{
for(int i = 0; i < 4; i++)
{
val = 1;
suit = " ";
name = " ";
suitNum++;
System.out.println();
System.out.println();
for(int z = 0; z < 13; z++)
{
if(suitNum == 1)
{
suit = "Hearts";
}
if(suitNum == 2)
{
suit = "Diamonds";
}
if(suitNum == 3)
{
suit = "Spades";
}
if(suitNum == 4)
{
suit = "Clubs";
}
if(val == 1)
{
name = "Ace";
}
else if(val == 11)
{
name = "Jack";
}
else if(val == 12)
{
name = "Queen";
}
else if(val == 13)
{
name = "King";
}
else {
name = "";
}
Card myCards = new Card(val, suit, name);
Deck.add(myCards);
System.out.print(myCards + " ");
val++;
}
}
}
public void Deal()
{
int size = 52 / 2;
for(int i = 0; i < size; i++)
{
Random();
for(int z = 0; z < cardCheck.length; z++)
{
if(cardCheck[i] == null)
{
cardCheck[i] = Deck.get(rnd);
play1.add(cardCheck[i]);
System.out.println(play1);
}
else
{
Random();
}
}
}
System.out.println();
System.out.println();
for(int i = 0; i < size; i++){
Deck.remove(play1.get(i));
}
for(int i = 0; i < size; i++){
play2.add(Deck.get(i));
}
for(int i = 0; i < size; i++)
{
System.out.println(play2.get(i));
}
}
public void Random()
{
rnd = (int)(Math.random() * 52) - decrease;
}
public void flip()
{
if(play1.indexOf(cardnum) >= play1.size() || play2.indexOf(cardnum2) >= play2.size())
{
cardnum = (int)(Math.random() * play1.size());
System.out.println(play1.get(cardnum));
cardnum2 = (int)(Math.random() * play2.size());
System.out.println(play2.get(cardnum2));
}
}
public void compare()
{
System.out.println("War!!!\n");
if(play1.get(cardnum).getNum() > play2.get(cardnum2).getNum())
{
System.out.println();
winner = 1;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play1.add(play2.get(cardnum2));
play2.remove(cardnum2);
System.out.println("Player 1 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() < play2.get(cardnum2).getNum())
{
System.out.println();
winner = 2;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play2.add(play1.get(cardnum));
play1.remove(cardnum);
System.out.println("Player 2 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() == play2.get(cardnum2).getNum())
{
System.out.println();
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
System.out.println("War!!");
winner = 0;
flip();
flip();
flip();
compare();
System.out.println();
printDecks();
}
}
public void playW()
{
while(play1.size() > 0 || play2.size() > 0)
{
flip();
compare();
}
}
public void printDecks()
{
for(int i = 0; i < play1.size(); i++)
{
System.out.print(play1.get(i) + " ");
}
System.out.println();
for(int i = 0; i < play2.size(); i++)
{
System.out.print(play2.get(i) + " ");
}
System.out.println();
System.out.println("Player 1 has: " + play1.size() + " cards");
System.out.println("Player 2 has: " + play2.size() + " cards");
}
}

This is more a comment but it became too long.
There is a lot to say about this code. Use switch case instead of series of if. Or at least use if else. What is the point of a for loop if you use cases inside? What is the 'i' variable for if you then increment yourself a suitNum variable? Don't use capital letter for methods. Only classes. Why does Random edits a variable and returns void? It would be more logical that random() returns the result you want and this way you get free of the useless variable 'rnd'
There is a lot more to say but it is a good start. About your error, in short, a stack overflow means that your program is using too much memory. This is especially common in code that contains an infinite recursive loop. Here, the infinite recursion is due to the compare method called inside the compare method...

and have little knowledge as to what this error even means besides my class doesn't have recursion done well.
Yes, your code has recursion, and it's easy to find. You know that the problem is coming from within the compare method, and so all you have to do is look within that method for compare() and find out where you're having the method call itself.
The solution is not to call the method within itself, and why should it be doing this anyway?
You're having the issue partly because your class structure is broken. The Deck class is class that should represent the structure and behavior of a deck of cards, nothing more and nothing less, It should have methods like public void shuffle(), like public Card Deal(), and such. It should not have any code that directly interacts with the user, and this code should go elsewhere, perhaps in your driver or Game class, or even as separate class(es) entirely.
I'm guessing that you'll also want to have a Hand class, one that holds a player's hand, and perhaps inside of this class, have a compare method that compares the current Hand with another Hand, passed in as a parameter.
You'll also want a Game class should have a game-loop that controls play, that ends when there is a winner or a draw, that holds the Deck, that holds 1 or more Player objects...
e.g.,
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
public enum Value {
//....
}
public class Card {
private Suit suit;
private Value value;
// TODO: constructor, methods including equals, hashCode
}
public class Deck {
private List<Card> cards = new ArrayList<>();
public Card deal() {
return cards.remove(0);
}
public void shuffle() {
Collection.shuffle(cards);
}
//....
}
class Player {
// either use a List in each Player or create a class called hand
private List<Card> hand;
private int cash;
private String name;
private Game game;
// TODO: constructor
// TODO: methods including receiveCard(Card c), List<Card> showHand(),...
}
public class Game {
private Player p1;
private Player p2;
private Deck deck;
private int moneyPot;

Related

Classifying Poker Hands in Java

I am currently working on a CS project that classifies player's hands. I solved the first half of the project to print out the deck, shuffled deck and the hands of player1, player2 and remaining deck. The problem comes up when I have to evaluate the hands. My code has to somehow evaluate which classification the hands are, and print out whether player1 or player2 wins. I have three classes so far:
public class Card {
static String[] card_suit = {"hearts", "diamonds", "clubs", "spades"};
static int[] card_rank = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};// 11 is Jack, 12 is Queen, 13 is King and 14 is Ace
public int[] getRank() {
return card_rank;
}
public String[] getSuit() {
return card_suit;
}
}
public class Driver {
public static void main(String[] args) {
Card card = new Card();
Deck deck = new Deck();
deck.getDeck();
System.out.print("ORIGINAL DECK: ");
deck.printDeck();
deck.shuffleDeck();
System.out.print("SHUFFLED DECK: ");
deck.printDeck();
System.out.println();
System.out.print("PLAYER ONE: ");
System.out.println(java.util.Arrays.toString(deck.playerOneHands()));
System.out.print("PLAYER TWO: ");
System.out.println(java.util.Arrays.toString(deck.playerTwoHands()));
System.out.print("REMAINING DECK: ");
System.out.println(java.util.Arrays.toString(deck.remainingDeckCards()));
}
}
import java.util.Arrays;
import java.util.Collections;
public class Deck extends Card {
Card card = new Card();
private String[] deck_card = new String[52];
public String[] getDeck() {
int i = 0;
for(int s = 0; s < 4; s++) {
for(int r = 0; r < 13; r++) {
deck_card[i]=(card_suit[s] + " of " + card_rank[r]);
i++;
}
}
return deck_card;
}
public void printDeck() {
System.out.println (java.util.Arrays.toString (deck_card));
}
public void shuffleDeck() {
Collections.shuffle(Arrays.asList(deck_card));
}
public String[] playerOneHands() {
String [] firsthand = new String[5];
for(int a = 0; a < 5; a++) {
firsthand[a] = deck_card[a];
}
return firsthand;
}
public String[] playerTwoHands() {
String[] secondhand = new String[5];
for(int a = 0; a < 5; a++) {
secondhand[a] = deck_card[a+5];
}
return secondhand;
}
public String[] remainingDeckCards() {
String[] remainDeck = new String[42];
for(int a = 0; a < 42; a++){
remainDeck[a] = deck_card[a+10];
}
return remainDeck;
}
}
What I thought it would work is because the Deck class extends from the Card class, I can use the getRank method to compare each hand, but I am not sure how to construct the conditionals.
Any help is greatly appreciated. Thanks.
For modelling the game, first identify entities like Card, Deck etc. (which mostly you have done). I would add few more like Player, Evaluator(explained below) etc.
Rank and Suit are NOT string/ int but they are predefined (not going to change in life time of game) possible variations in Cards. Always use domain vocabulary for best model. Each Card belongs to one Suit and one Rank. (think of making Rank and Suit as enums, this will avoid unknown values breaking the code at run time.
Not giving set method for suite and rank in Card is essential (they form an identity of Card in combination)
Full Deck (at initialization) is formed by cross product of Suit and Rank. Meaning Deck has (contains) multiple cards. Remember Card can be alive outside of Deck (when in players hand) as well, hence its not composition. Inheriting Deck from Card is absolutely wrong. It translates to statement Deck is a kind of Card, which is not correct. Deck will have collection of Cards. Using inheritance, will lead to violation of Liskov's Substitution Principle (One of the SOLID).
To model Deck, consider the fact that Deck does not contain duplicate cards, Deck does not change its order once formed (unless shuffled). This being tricky selection between Set and List, I would go for List with added programmatic constraint for avoiding duplicates (needs to be done only when initialization).
But instead of Modelling Deck as java collection, it will be best to let class Deck contain java collection of suitable choice and Deck class work as wrapper by defining required API (from domain perspective) like shuffle, getTopCard() etc. This is called as Object Adapter design pattern. This makes our design platform (implementation) independent.
You need to model few more classes like Player holds CardInHand etc.
About evaluating Cards in hand, its better to model it as separate class as its different concern and rules can change independent of other classes.
Poker game is best assignment to learn Object Oriented Programming.
Without wanting to do your homework for you...
This is a problem:
class Deck extends Card
A deck isn’t a subtype of a card. A deck has cards, so:
class Deck {
List<Card> cards;
}
is a better choice.
Also, the following code does nothing to the deck:
public void shuffleDeck() {
Collections.shuffle(Arrays.asList(deck_card));
}
It shuffles a copy of the deck, leaving the deck untouched.
Also, you shouldn’t be building strings in a loop. Instead, implement (override) a toString() method on Card and Deck.
Also, make suit an enum.
Also, delete card_rank entirely - it serves no purpose. Instead, add a int rank; field to Card, or better make rank an enum.
Fix these things first, then re-attack the problem by writing a method that is passed a Hand (a new class) that has a List and a method that returns a HandType (another enum) by evaluating if the hand is a straight flush, else four of a kind, else ... all the way down to high card - highest to lowest.
It seems that you class Card only has static fields; I would change it so that an instance of Card would represent a single card from a Deck. I would also make the suites an enum type. You can also add integer constants for the figures and aces. The class can implement Comparable<Card>:
public class Card implements Comparable<Card> {
public enum Suite {CLUBS, DIAMONDS, HEARTS, SPADES};
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int ACE = 14;
public final Suite suite;
public final int rank;
public Card(Suite suite, int rank) {
if (suite == null) {
throw new IllegalArgumentException("Suite cannot be null");
}
if (rank < 2 || rank > 14) {
throw new IllegalArgumentException(
"Value must be between 2 and 14");
}
this.suite = suite;
this.rank = rank;
}
public Suite getSuite() {
return suite;
}
public int getRank() {
return rank;
}
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
if (rank >= 2 && rank <= 10) {
buf.append(rank);
} else {
switch (rank) {
case JACK:
buf.append("jack");
break;
case QUEEN:
buf.append("queen");
break;
case KING:
buf.append("king");
break;
case ACE:
buf.append("ace");
break;
}
}
buf.append(" of ");
buf.append(suite.toString().toLowerCase());
return buf.toString();
}
#Override
public int compareTo(Card other) {
if (rank > other.rank) {
return 1;
} else if (rank < other.rank) {
return -1;
} else {
return suite.compareTo(other.suite);
}
}
}
Note that you could also have two subclasses of Card: one for the numbers and one for the figures.
The Deck is a collection of 52 cards. It is initialised by adding each card to a list. One can shuffle a deck, or take a card from the deck:
public class Deck {
private final List<Card> cards = new ArrayList<>();
public Deck() {
for (Card.Suite suite: Card.Suite.values()) {
for (int i = 2; i <= 14; ++i) {
cards.add(new Card(suite,i));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
public boolean isEmpty() {
return cards.isEmpty();
}
public Card take() {
if (cards.isEmpty()) {
throw new IllegalStateException("Deck is empty");
}
return cards.remove(0);
}
}
You can take shuffle and take 5 cards from the deck like this:
Deck deck = new Deck();
deck.shuffle();
for (int i = 0; i < 5; ++i) {
Card card = deck.take();
System.out.println(card);
}
Now a Hand is a set of five cards taken from a Deck. We can declare Hand as implementing Comparable<Hand> so that we can know which of two hands have the highest value:
public class Hand implements Comparable<Hand> {
private final Card[] cards = new Card[5];
public Hand(Deck deck) {
for (int i = 0; i < 5; ++i) {
cards[i] = deck.take();
}
Arrays.sort(cards);
}
#Override
public int compareTo(Hand other) {
...
}
}
Now here comes the fun part: you must identify the hand type as one of the following (enum type):
public enum HandType {
SINGLE, PAIR, TWO_PAIRS, THREE, STRAIGHT, FLUSH, FULL_HOUSE, FOUR,
STRAIGHT_FLUSH, ROYAL_FLUSH;
}
Note that the constants are arranged from the lowest to the highest. In addition, the cards must be arranges so that in case of a tie, you can compare the cards to identify the winner.
I would suggest you make groups of cards of same rank; in the case where you have five different groups, it still can be a flush or a straight.
Another approach would consist in declaring a subclass of Hand for each HandType, but I don't think you would gain much by doing this.
public class Hand implements Comparable<Hand> {
public enum HandType {
SINGLE, PAIR, TWO_PAIRS, THREE, STRAIGHT, FLUSH, FULL_HOUSE, FOUR,
STRAIGHT_FLUSH, ROYAL_FLUSH;
}
private final Card[] cards = new Card[5];
private final int[] groupSize;
private final HandType type;
public Hand(Deck deck) {
for (int i = 0; i < 5; ++i) {
cards[i] = deck.take();
}
groupSize = group(cards);
type = identifyType(groupSize, cards);
}
#Override
public int compareTo(Hand other) {
int r = type.compareTo(other.type);
if (r != 0) {
return r;
}
for (int i = cards.length; --i >= 0; ) {
int r1 = cards[i].getRank();
int r2 = other.cards[i].getRank();
if (r1 < r2) {
return -1;
} else if (r1 > r2) {
return 1;
}
}
return 0;
}
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(type);
buf.append(": ");
buf.append(cards[0]);
for (int i = 1; i < 5; ++i) {
buf.append(", ");
buf.append(cards[i]);
}
return buf.toString();
}
private static int[] group(Card[] cards) {
Arrays.sort(cards);
List<List<Card>> groups = new ArrayList<>();
int val = -1; // invalid rank
List<Card> currentGroup = null;
for (Card card: cards) {
if (val == card.getRank()) {
currentGroup.add(card);
} else {
if (currentGroup != null) {
groups.add(currentGroup);
}
currentGroup = new ArrayList<>();
currentGroup.add(card);
val = card.getRank();
}
}
if (currentGroup != null) {
groups.add(currentGroup);
}
// identify groups of cards of same value
// sort groups by size and highest card
Collections.sort(groups, (List<Card> group1, List<Card> group2) -> {
int s1 = group1.size();
int s2 = group2.size();
if (s1 < s2) {
return -1;
} else if (s1 > s2) {
return 1;
} else {
return group1.get(s1-1).compareTo(group2.get(s2-1));
}
});
int[] groupSize = new int[groups.size()];
int g = 0;
int i = 0;
for (List<Card> group: groups) {
groupSize[g++] = group.size();
for (Card card: group) {
cards[i++] = card;
}
}
assert sum(groupSize) == 5;
return groupSize;
}
private static HandType identifyType(int[] groupSize, Card[] cards) {
switch (groupSize.length) {
case 2:
// can be a full house or four cards
if (groupSize[0] == 1) {
return HandType.FOUR;
} else if (groupSize[0] == 2) {
return HandType.FULL_HOUSE;
} else {
assert false;
return null;
}
case 3:
if (groupSize[0] == 1) {
// three cards or double pair
if (groupSize[1] == 1) {
return HandType.THREE;
} else {
assert groupSize[1] == 2 && groupSize[2] == 2;
return HandType.TWO_PAIRS;
}
} else {
assert false;
return null;
}
case 4:
// one pair
return HandType.PAIR;
case 5:
// all different values: check for flush
Card prev = cards[0];
boolean sameSuite = true;
boolean straight = true;
for (int i = 1; i < 5; ++i) {
Card card = cards[i];
straight &= card.getRank() == prev.getRank()+1;
sameSuite &= card.getSuite() == prev.getSuite();
}
if (sameSuite) {
if (straight) {
if (cards[4].getRank() == Card.ACE) {
return HandType.ROYAL_FLUSH;
}
return HandType.STRAIGHT_FLUSH;
} else {
return HandType.FLUSH;
}
} else {
if (straight) {
return HandType.STRAIGHT;
} else {
return HandType.SINGLE;
}
}
default:
assert false;
return null;
}
}
private static int sum(int[] groupSize) {
int sum = 0;
for (int s: groupSize) {
sum += s;
}
return sum;
}
}

Card Game Adding cards to a set of "hands" --Java

I am trying to make a basic outline for a card game, I have the deck created, a method created for dealing a random card but I am having difficulty for adding the card into the actual hand. The issue is in the Game class with the getCard() method. I do not know the correct way to do this, since my idea did not work.
Class to create the deck:
import java.util.Random;
public class Deck<E> {
//create a new linked list for Deck
LinkedPositionalList deck = new LinkedPositionalList();
public Deck(){
for (int i = 0; i < 4; i++){
for(int j = 2; j< 14; j++){
Card card = new Card(i,j);
deck.addLast(card); //add to linked list
}
}
}
public Card card(){
Random rand = new Random();
int position = rand.nextInt(52);//create random number 0-52
int counter = 0;
Iterator<Card> iter = this.deck.iterator();
while(counter <= position){
Card card = iter.next();
if(counter == position){
iter.remove();
return card;
}
counter++;
}
return null;
}
}
Class to create the card:
public class Card<E> {
public final static int CLUBS = 0,
SPADES = 1,
DIAMONDS = 2,
HEARTS = 3;
private final static String [] suitNames = {"CLUBS", "SPADES", "DIAMONDS", "HEARTS"};
// Special cards
private int JACK_VALUE = 11;
private int QUEEN_VALUE = 12;
private int KING_VALUE = 13;
private int ACE_VALUE = 14;
// The card
private int suit = 0; // Suit of the card
private int value = 2; // Value of the card
public int getSuit() {
return this.suit;
}
public int getValue() {
return this.value;
}
public Card(int suit, int value ){
this.suit = suit;
this.value = value;
}
public String suitToString() {
return suitNames[ suit ];
}
public String valueToString() {
if (value == ACE_VALUE) {
return "ACE";
} else if (value == JACK_VALUE) {
return "JACK";
} else if (value == QUEEN_VALUE) {
return "QUEEN";
} else if (value == KING_VALUE) {
return "KING";
} else if ( value > 0 ) {
return String.valueOf(value);
}
return "";
}
public String shortValueToString() {
if (value == ACE_VALUE) {
return " A";
} else if (value == JACK_VALUE) {
return " J";
} else if (value == QUEEN_VALUE) {
return " Q";
} else if (value == KING_VALUE) {
return " K";
} else if ( value > 0 ) {
return String.format("%2d",value);
}
return "";
}
public String toString() {
return valueToString() + " of " + suitToString();
}
public String toShortString() {
return shortValueToString() + suitToString().substring(0,1);
}
public boolean equalTo(Card c ) {
if ( c.getSuit() != this.getSuit()) return false;
if ( c.getValue() != this.getValue()) return false;
return true;
}
}
Class to create the hand:
public class CardHand<E> {
LinkedPositionalList<E> hand = new LinkedPositionalList();
//TODO: create method to order hand
}
Class to initialize the game:
public class Game{
int players;
int maxCardsInHand;
int decks;
CardHand[] hand;
Card card;
Deck deck;
//constructor
public Game(int player, int max, int numDecks){
players = player;
maxCardsInHand = max;
decks = numDecks;
this.hand = new CardHand[player];
for(int index = 0; index < hand.length; index++){
this.hand[index] = new CardHand();
}
}
public void getCard(){
System.out.println("You got this far...");
card = deck.card();
for(int index = 0; index < hand.length; index++){ //to add to each players hands
hand[index] = card; //issues with this part
}
//TODO: ordered correctly by suit AND value
}
Given that the call iter.remove(); works, your deck gets smaller and smaller each time you call the card() method. Yet you assume you can iterate thru a full deck:
rand.nextInt(52);
Instead, iterate only over the cards you have left:
rand.nextInt(this.deck.size());
If there is no size() or length() method for the list object, decrease a counter each time card() is called:
rand.nextInt(cardsInDeck++);

Java 2 player trivia game

I am having some trouble with this, and I would greatly appreciate some help. I am still a "noobie" when it comes to java so please understand that I probably will have stupid mistakes. Anyways, I am trying to make a two player java game and I keep getting errors that I do not understand. I have three separate classes. This is my main class
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Assignment3
{
public static void main(String args[]) throws IOException
{
// Constants
final int NUM_QUESTIONS = 10;
final int NUM_PLAYERS = 2;
// Variables
int playerTurn = 1; // The current player
int questionNum; // The current question number
int playerAnswer; // The player's chosen answer
int player1points = 0; // Player 1's points
int player2points = 0; // Player 2's points
// Create an array of Player objects for player #1 and player #2.
player[] players = new player[NUM_PLAYERS];
for (int i = 0; i < NUM_PLAYERS; i++)
{
players[i] = new player(i+1);
}
// Create an array to hold Question objects.
questions[] questions = new questions [NUM_QUESTIONS];
// Initialize the array with data.
intQuestion(questions);
// Play the game.
for (int i = 0; i < NUM_QUESTIONS; i++)
{
// Display the question.
Assignment3.displayQuestion(qArray[i], playerTurn);
// Get the player's answer.
players[playerTurn - 1].chooseAnswer();
// See if the correct answer was chosen.
if (qArray[i].getCorrectAnswerNumber() == players[playerTurn - 1].getCurrentAnswer())
{
players[playerTurn -1].incrementPoints();
}
// See if the the player chose the wrong answer.
// do nothing
// Switch players for the next iteration.
if (playerTurn == 1)
playerTurn = 2;
else
playerTurn = 1;
}
// Show the game results.
showGameResults(players);
}
/**
* The initQuestions method uses the contents of the trivia.txt file to
* populate the qArray parameter with Question objects.
*/
public static void initQuestions(questions qArray[]) throws IOException
{
// Open the trivia.txt file.
File file = new File("trivia.txt");
Scanner inputFile = new Scanner(file);
// Populate the qArray with data from the file.
for (int i = 0; i < qArray.length; i++)
{
// Create a Question object in the array.
qArray[i] = new questions();
// Get the question text from the file.
qArray[i].setQuestion(inputFile.nextLine());
// Get the possible answers.
for (int j = 1; j <= 4; j++)
{
qArray[i].setPossibleAnswer(inputFile.nextLine(), j);
}
// Get the correct answer.
qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));
}
}
public static void displayQuestion(questions q, int playerNum)
{
// Display the player number.
System.out.println("Question for player #" + playerNum);
System.out.println("------------------------");
// Display the question.
System.out.println(q.getQuestionText());
for (int i = 1; i <= 4; i++)
{
System.out.println(i + ". " + q.getPossibleAnswer(i));
}
}
public static void showGameResults(player[] players)
{
// Display the stats.
System.out.println("Game Over!");
System.out.println("---------------------");
System.out.println("Player 1's points: " + players[0].getPoints());
System.out.println("Player 2's points: " + players[1].getPoints());
// Declare the winner.
if (players[0].getPoints() > players[1].getPoints())
System.out.println("Player 1 wins!");
else if (players[1].getPoints() > players[0].getPoints())
System.out.println("Player 2 wins!");
else
System.out.println("It's a TIE!");
}
}
This is my player class
import java.util.Scanner;
public class player
{
private int playerNumber; // The player number
private int points; // Player's points
private int currentAnswer; // Current chosen answer
//Constructor
public player(int playerNum)
{
playerNumber = playerNum;
points = 0;
}
public void chooseAnswer()
{
// Create a Scanner object for keyboard input.
// Get the user's chosen answer.
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your Answer"); //Asks user for a number
this.currentAnswer = keyboard.nextInt();
}
public int getCurrentAnswer()
{
return this.currentAnswer; //Returns Current Answer
}
public void incrementPoints()
{
this.points++; //Increments the points
}
public int getPoints()
{
return this.points; //Returns the points
}
}
This is my questions class
public class questions
{
// Constant for the number of answers
public final int NUM_ANSWERS = 10;
// The trivia question
private String questionText;
// An array to hold possible answers.
private String possibleAnswers[] = new String[NUM_ANSWERS];
// The number (1, 2, 3, or 4) of the correct answer.
private int correctAnswer;
//Constructor
public questions()
{
// Initialize all fields to "" or 0;
questionText = "";
correctAnswer = 0;
for (int i = 1; i < NUM_ANSWERS; i++)
setPossibleAnswer("", i);
}
public void setQuestion(String question)
{
//Sets the question
this.questionText = question;
}
public void setPossibleAnswer(String text, int num)
{
//Sets possible Answer
this.possibleAnswers[num] = text;
}
public void setCorrectAnswerNumber(int num)
{
//Sets correct Answer
this.correctAnswer = num;
}
public String getQuestionText()
{
//Returns Question Text
return this.questionText;
}
public String getPossibleAnswer(int num)
{
//Returns Possible Amswer
return this.possibleAnswers[num];
}
public int getCorrectAnswerNumber()
{
//Returns Correct Answer
return this.correctAnswer;
}
public String getCorrectAnswer()
{
//Returns Possible Answer
return this.possibleAnswers[this.correctAnswer];
}
}
If there is any help you guys can offer, I would greatly appreciate. I just can't seem to figure out why I keep getting these errors that are stopping it from running. Please and thank you.
these are the errors I get, I don't know if this is what you mean, I found out what I had earlier was from something else
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method intQuestion(questions[]) is undefined for the type Assignment3
qArray cannot be resolved to a variable
qArray cannot be resolved to a variable
at Assignment3.main(Assignment3.java:42)
Your method is named initQuestion, but you are calling intQuestion.
Oh, and you are using qArray outside of initQuestion, the only place where it seems to be defined.

how to get the enum values one by one using a loop

i'm trying to get the enum values one by one using a for loop without the need to specify all possible values like i'm doing in the code Value.As be replaced by something like Value.values()but when i try this it doesn't work for me :
public class Deck {
private LinkedList<Card> cardList;
public Deck(int nbBox) {
this.cardList = new LinkedList<Card>();
for (int i = 0; i < nbBox; i++) {
for (int j = 0; j < 52; j++) {
cardList.add(new Card(Value.AS, Color.CLUB));
}
}
}
public Card draw() {
return null; // not done yet
}
#Override
public String toString() {
return "Here is the deck : " +cardList;
}
public LinkedList<Card> getCardList() {
return cardList;
}
public void setCardList(LinkedList<Card> cardList) {
this.cardList = cardList;
}
}
You could use a for-each loop on the values(). This reads as for each suit, for each value add a new card with the suit and value to the List. Also, you could use diamond operator <> like,
public Deck(int nbBox) {
this.cardList = new LinkedList<>(); // <-- diamond operator
for (int i = 0; i < nbBox; i++) {
for (Suit suit : Suit.values()) {
for (Value value : Value.values()) {
cardList.add(new Card(suit, value));
}
}
}
}
Try this:
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret = Mobile.Samsung;
System.out.println("The ordinal is = " + ret.ordinal());
System.out.println("MobileName = " + ret.name());
}
}
The output will be:
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
The ordinal is = 0
MobileName = Samsung

Card c in video poker

I'm working on a video poker assignment in java. We are given class templates that we are supposed to use in our program. I'm confused as to what Card c represents. Like in the method addCard(Card c), does that just mean it will be executed on the Card object that's currently in use? Here are the class files I've been working on so far. They are far from finished.
Player Class:
import java.util.ArrayList;
public class Player {
private ArrayList<Card> hand; // the player's cards
// you will likely need more instance variables
public Player(){
ArrayList<Card> hand = new ArrayList;
}
public void addCard(Card c){
// add the card c to the player's hand
}
public void removeCard(Card c){
// remove the card c from the player's hand
}
// you will likely need more methods here
}
Deck class:
import java.util.Random
public class Deck {
private Card[] theDeck;
private int top;
// add more instance variables if needed
public Deck(){
top = 0
Card[] theDeck = new Card[52];
for(int s = 1; s <= 4; s++)
{
for (int v = 1; v <= 13; v++)
{
for (int i = 0; i < theDeck.length; i++)
theDeck[i] = new Card(s,v);
}
public void shuffle()
{
// shuffle the deck here
Random generator = new Random();
int i;
int j;
int temp = i;
int i = generator.nextInt(51) + 1;
int j = generator.nextInt(51) + 1;
for(int k = 1; k <100; k++)
{
theDeck[i] = theDeck[j];
theDeck[j] = temp;
}
top = 0;
}
public Card deal(){
// deal the top card in the deck
if (top < 40)
{
theDeck.shuffle;
}
return theDeck[top];
top++;
} //this method should add cards to array hand? no addCard will do that.
// add more methods here if needed
//DB getter methods here?
}
Card Class:
public class Card implements Comparable<Card>{
private int suit;
private int value;
public Card(int s, int v){ //constructor of an object Card
s = suit;
v = value;
//make a card with suit s and value v
}
public int compareTo(Card c){
// use this method to compare cards so they
// may be easily sorted
}
public String toString() //to tell the user what card/s they have
{
myCard.getSuit();
myCard.getValue();
if(s == 1)
{
if(v == 11)
{
return "Jack of Clubs";
}
if(v == 12)
{
return "Queen of Clubs";
}
if(v == 13)
{
return "King of Clubs";
}
if(v == 1)
{
return "Ace of Clubs";
}
else{
return v + " of Clubs";
}
}
if(s == 2)
{
return v + "Diamonds";
}
if(s == 3)
}
return v + "Hearts";
}
if(s == 4)
}
return v + "Spades";
}
//DB method to set 1, 2, 3, and 4 to card suits
//now here create string representation for the Card
// use this method to easily print a Card object
public int getSuit()
{
return s;
}
public int getValue()
{
return v;
}
//DB right now have cards in theDeck like Card(2, 10), need Card(d, 10)
//need to convert that to a String d10
}
// add some more methods here if needed
}
In public void addCard(Card c), c is a parameter.
This means that within the body of the function addCard, you can refer to the value passed to the function by the name c. You call the function addCard with some value (e.g., theDeck[0]), and that value will be used in addCard().

Categories