I'm writing the code for a HiLo card game in which the player has to guess whether the next card drawn will be higher, lower or equal.
Although for the numbers 11, 12, 13 and 1, I'd like the output to be Jack, Queen, King and Ace.
I've worked out the program to point where it returns a random int between 0 and 13 (I'm still unaware as to how I would write the code to make it only choose random int between 1 and 13).
How do I set it so the 11, 12, 13 and 1 numbers appear as
The Card pulled is the Ace,
is the next card Higher, Lower or Equal?
and so on, I've tried if statements and changing int to String, but neither work, and to my avail was nothing I was able to find about a String generator...
Here is my code, any help would be greatly appreciated
import java.util.Random;
import javax.swing.JOptionPane;
public class HiLo {
public static final int JACK = 11;
public static final int QUEEN = 12;
public static final int KING = 13;
public static final int ACE = 1;
public static void main(String[] args) {
int correctGuesses = 0;
Random generator = new Random();
int currentCard;
int nextCard = generator.nextInt( KING+1 );
while (correctGuesses < 4) {
currentCard = nextCard;
nextCard = generator.nextInt( KING+1 );
Object[] options = {"Higher",
"Lower",
"Equal"};
int Input = JOptionPane.showOptionDialog(null,
"The Card pulled is the " + currentCard +
" \nis the next card Higher, Lower or Equal?",
"HiLo Card Game",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
if(nextCard > currentCard) {
switch(Input) {
case JOptionPane.YES_OPTION:
correctGuesses++;
break;
case JOptionPane.NO_OPTION:
case JOptionPane.CANCEL_OPTION:
correctGuesses = 0;
break;
}
} else if(nextCard < currentCard) {
switch(Input) {
case JOptionPane.NO_OPTION:
correctGuesses++;
break;
case JOptionPane.YES_OPTION:
case JOptionPane.CANCEL_OPTION:
correctGuesses = 0;
break;
}
} else {
switch(Input) {
case JOptionPane.CANCEL_OPTION:
correctGuesses++;
break;
case JOptionPane.YES_OPTION:
case JOptionPane.NO_OPTION:
correctGuesses = 0;
break;
}
}
}
JOptionPane.showMessageDialog(null,
"Congratulations, You guessed correctly 4 times,"
+ "\nthe Last Card was the " + nextCard + ", resart to play again" );
}
}
Change currentCard to a String. Then instead of
currentCard = nextCard;
do
currentCard = Integer.toString(nextCard);
Then you can do your if statements and assign the strings you need to for the output.
String getCardString(int card) {
String cardString = null;
switch (card) {
ACE:
cardString = "ace";
break;
KING:
cardString = "king";
break;
// same for queen and jack
DEFAULT:
cardString = Integer.toString(nextCard);
}
return cardString;
}
JOptionPane.showMessageDialog(null,
"Congratulations, You guessed correctly 4 times,"
+ "\nthe Last Card was the " + getCardString(nextCard) + ", resart to play again" );
For the random generator, you can generate between 0 and 12, then add 1:
nextCard = ACE + generator.nextInt(KING);
Related
I've got an assignment that requires me to have the user guess a random color generated by the program, then display the total results. My code works fine, but I'm wanting to break it down into another method. Specifically, the section that receives input from the user. I want that in its own method, then the main method only displaying results. I tried creating a new object for the user's color choice, but that didn't work. I'm not sure what to do next. Thank you for your time!
import java.util.Scanner;
import java.util.Random;
public class ESP
{
public static void main(String[] args)
{
String colorChoice;
int correct = 0, incorrect = 0;
Scanner keyboard = new Scanner(System.in);
for(int i = 1; i <= 10; i++)
{
System.out.print("Choose either red, green, blue, orange or yellow! ");
colorChoice = keyboard.nextLine();
System.out.println("You chose: " + colorChoice);
String computerChoice = computerColorChoice();
System.out.println("The computer chose: " + computerChoice);
if(colorChoice.equalsIgnoreCase(computerChoice))
{
correct++;
}
else
{
incorrect++;
}
}
System.out.println("Amount of times you guessed correctly: " + correct);
System.out.println("Amount of times you guess incorrectly: " + incorrect);
}
public static String computerColorChoice()
{
String randomColor;
int randomNumber;
Random random = new Random();
randomNumber = random.nextInt(4);
switch (randomNumber)
{
case 0:
randomColor = "Red";
break;
case 1:
randomColor = "Green";
break;
case 2:
randomColor = "Blue";
break;
case 3:
randomColor = "Orange";
break;
case 4:
randomColor = "Yellow";
break;
default:
randomColor = " ";
}
return randomColor;
}
}
You can add a method for the user choice:
public static String userColorChoice()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Choose either red, green, blue, orange or yellow! ");
String userColorChoice = keyboard.nextLine();
System.out.println("You chose: " + userColorChoice);
return userColorChoice;
}
Also you can update your computerColorChoice as follows:
public static String computerColorChoice()
{
String randomColor;
int randomNumber;
Random random = new Random();
randomNumber = random.nextInt(4);
switch (randomNumber)
{
case 0:
randomColor = "Red";
break;
case 1:
randomColor = "Green";
break;
case 2:
randomColor = "Blue";
break;
case 3:
randomColor = "Orange";
break;
case 4:
randomColor = "Yellow";
break;
default:
randomColor = " ";
}
System.out.println("The computer chose: " + randomColor);
return randomColor;
}
And finally update your main:
public static void main(String[] args)
{
int correct = 0, incorrect = 0;
for(int i = 1; i <= 10; i++)
{
if(userColorChoice().equalsIgnoreCase(computerColorChoice()))
correct++;
else
incorrect++;
}
System.out.println("Amount of times you guessed correctly: " + correct);
System.out.println("Amount of times you guess incorrectly: " + incorrect);
}
I hope this help you.
I am building a war card game for an assignment I have the game built and it is working but I am running into the issue such as card 10 jack of spades is less in value as say card 23 the jack of hearts. Looking for advice about the best way to be able to compare the cards to see if they are equal.
Below is the code I have so far:
import java.util.Random;
import java.util.Scanner;
public class WarGame {
public static void main(String a[]) {
DeckOfCards d = new DeckOfCards();
int input = 0;
int computer = 0;
int you = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
while (input != 2) {
if (input == 1) {
System.out.print("\n\nEnter the value of the card:");
int card = sc.nextInt();
if (card >= 0 && card <= 51) {
int systemCard = d.computerTurn(card);
System.out.println("Your card - " + d.inputCard(card));
System.out.println("Computer card - " + d.inputCard(systemCard));
if(systemCard > card)
++computer;
else
++you;
System.out.println("The winner is " + (systemCard > card ? "Computer" : "You"));
} else {
System.out.println("Invalid card");
}
}
else {
System.out.println("That is an invalid selection please choose 1 or 2.");
}
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
}
System.out.println("Total Wins by Computer: "+ computer);
System.out.println("Total Wins by You: "+ you);
if (computer > you)
System.out.println("Computer is the champion");
else if (computer == you)
System.out.println("Its a Tie");
else
System.out.println("You are the champion");
}
}
class DeckOfCards {
String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
Random ran = new Random();
int systemWin = 0;
int playerWin = 0;
String inputCard(int card) {
int suit = card / 13; //assigning suit to your card
int rank = card % 13; //Assigning rank to your card
String out = "";
switch (rank) { //Setting up face cards for the cases
case 0:
out = "Ace of " + suits[suit];
break;
case 10:
out = "Jack of " + suits[suit];
break;
case 11:
out = "Queen of " + suits[suit];
break;
case 12:
out = "King of " + suits[suit];
break;
default:
out = rank + 1 + " of " + suits[suit]; //Adding one to remainder so it will go from 2-10 instead of 1-9
break;
}
return out;
}
int computerTurn(int playerRank) { //Keeping track of the wins for computer and player
int systemRank = this.ran.nextInt(51);
if (systemRank > playerRank)
systemWin++;
else
playerWin++;
return systemRank;
}
}
I think you're comparing the index to your deck rather than the card values themselves. If I'm understanding, you want to compare d.inputCard(card) with d.inputCard(systemCard) instead of card with systemCard. But of course, that's a String. Having a hard time following the code :-).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi there I am trying to get this to calculate the winner from 4 players (The game is the classic card game war) but I can only get it to do two. the first bit of the code is my Card class and the second bit is the main program where there are more if statements for working out the winner. the issue i'm having is with the method "getWinner". I have included the deck class also if that is needed (at the bottom).
package warcard;
public class Card
{
private int value, suit;
private String result, suitStr;
/**
* #param num represents value of card
* #param type represents the suit of card
*/
public Card(int num, int type)
{
/**
* Class constructor.
*/
value = num;
suit = type;
switch(value)
{
case 1: result = "Ace";
break;
case 2: result = "Two";
break;
case 3: result = "Three";
break;
case 4: result = "Four";
break;
case 5: result = "Five";
break;
case 6: result = "Six";
break;
case 7: result = "Seven";
break;
case 8: result = "Eight";
break;
case 9: result = "Nine";
break;
case 10: result = "Ten";
break;
case 11: result = "Jack";
break;
case 12: result = "Queen";
break;
case 13: result = "King";
break;
default: result = "";
break;
}
switch(suit)
{
case 1: suitStr = "Clubs";
break;
case 2: suitStr = "Diamonds";
break;
case 3: suitStr = "Hearts";
break;
case 4: suitStr = "Spades";
break;
}
}
/**
* getters
*/
public int getNum()
{
return value;
}
public int getSuit()
{
return suit;
}
/**
* setters
*/
public void setVal(int choice)
{
value = choice;
}
public void setSuit(int choice)
{
suit = choice;
}
/**
* #param play represents Cards object
* #return flag the String result of the game
*/
public String getWinner(Card play)
{
String flag = "";
if(value == play.getNum())
{
if(suit > play.getSuit())
flag = "win";
else if (suit == play.getSuit())
flag = "tie";
else
flag = "lose";
}
else if (value > play.getNum())
flag = "win";
else
flag = "lose";
return flag;
}
/**
* toString method
*/
public String toString()
{
String info = "";
info = info + result + " of " + suitStr;
return info;
}
} /** end Cards class */
main program
package warcard;
public class Warcard
{
public static void main(String[] args)
{
// instantiation of 2 decks
Deck hand1, hand2, hand3, hand4;
hand1 = new Deck();
hand2 = new Deck();
hand3 = new Deck();
hand4 = new Deck();
String result = "";
// shuffle the decks
hand1.shuffle();
hand2.shuffle();
hand3.shuffle();
hand4.shuffle();
/** tracker variables
* wins1 tracks user's wins
* wins2 tracks computer's wins
*/
int count = 0;
int wins1 = 0;
int wins2 = 0;
int wins3 = 0;
int wins4 = 0;
int ties = 0;
for (int i= 0; i < 52; i++)
{
Card tester = hand1.getCard(count);
Card tester2 = hand2.getCard(count);
Card tester3 = hand3.getCard(count);
Card tester4 = hand4.getCard(count);
count++;
System.out.println("Player 1's hand: " + tester);
System.out.println("Player 2's hand: " + tester2);
System.out.println("Player 3's hand: " + tester3);
System.out.println("Player 4's hand: " + tester4);
result = tester.getWinner(tester2);
if(result == "win")
{
System.out.println("Win!");
wins1++;
}
else if(result == "tie")
{
System.out.println("Tie!");
ties++;
}
else
{
System.out.println("Lose!");
wins2++;
}
} // end for loop
System.out.println();
System.out.println("Total score:");
System.out.println();
System.out.println("Player 1's wins: " + wins1 + "\n" + "Player 2's wins: " + wins2 + "\n" + "Player 3's wins: " + wins3 + "\n" + "Player 4's wins: " + wins4 + "\n" + "Ties: " + ties);
if (wins1 > wins2 && wins1 > wins3 && wins1 > wins4)
System.out.println("Player 1 won the game!");
else if(wins2 > wins1 && wins2 > wins3 && wins2 > wins4)
System.out.println("Player 2 wins!");
else if(wins3 > wins1 && wins3 > wins2 && wins3 > wins4)
System.out.println("Player 3 wins!");
else if(wins4 > wins1 && wins4 > wins2 && wins4 > wins3)
System.out.println("Player 4 wins!");
else if(wins1 == wins2 && wins1 == wins3 && wins1 == wins4)
System.out.println("It's a tie!");
} // end main
} // end class
Deck class
package warcard;
import java.util.Random;
public class Deck
{
private Card[] deck;
private int[] suit = {1, 2, 3, 4};
private int[] numbers = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
private int count;
public Deck()
{
deck = new Card[52];
count = 0;
for(int i = 0; i <= 3; i++)
{
for(int k = 2; k <= 14; k++)
{
deck[count] = new Card(k, suit[i]);
count++;
}
} /**
* end outer loop
*/
}
/**
* end constructor
*/
public Card getCard(int index)
{
return deck[index];
}
public void shuffle()
{
int rand;
Random mix = new Random();
for (int i = 0; i < deck.length; i++)
{
/**
* shuffles deck
*/
rand = mix.nextInt(deck.length);
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
} /**
* end for loop
*/
}
} /** end DeckCards class */
Currently, you are only comparing the values of 2 cards; you're comparing tester against tester2, but do not include player 3 or player 4's cards. Not only that, you don't return which player has won. Instead, you only specify whether p1 has won or lost.
Your String getWinner(Card) method needs more parameters, so you can pass more cards into it. Compare against all the cards. It should also return which player has won:
public String getWinner(Card p2, Card p3, Card p4) {
//compare against ALL cards
//return which player won
}
You would then call this, passing in all opposing cards, not just tester2:
result = tester.getWinner(tester2, tester3, tester4);
Finally, you have to fix up your score keeper. Instead of checking for "win" or "lose", check for which player won:
/* could use a switch statement */
if(result == "p1") {
System.out.println("Player 1 wins!");
wins1++;
} else if(result == "p2") {
System.out.println("Player 2 wins!");
wins2++;
} else if(result == "p3") {
//...
}
If I were on a computer, I'd suggest a LOT more, such as encapsulating the "battle" somewhere else rather than within the first player's Card; I recommend posting to CodeReview once you are done. If you have any problems, let me know.
As far as I can see, only the tester-deck is playing against the tester2-deck. If thats not intended, the reason, only 2 of your 4 decks are "competitive" ist that only 2 of them do play, right?
Whenever I run the code, if any of the players gets an ace, king, queen, or jack, I get the following error :
Exception in thread "main" java.lang.NumberFormatException: For input string: "Ace"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Card.getCard(Card.java:19)
at Card.main(Card.java:37)
this is the code I have so far :
public class Card
{
String suit;
String rank;
int getCard;
int a;
int b;
int getSuit;
public Card(){
String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};
String [] xRank = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
a = ((int)(Math.random() * 4));
b = ((int)(Math.random() * 13));
suit = xSuit[a];
rank = xRank[b];
}
int getCard(){
getCard = Integer.parseInt (rank);
return getCard;
}
int getSuit(){
getSuit = Integer.parseInt (suit);
return getSuit;
}
public static void main(String[] args)
{
Card player = new Card();
Card player2 = new Card();
System.out.println("WAR");
System.out.println("--------------");
System.out.println("You played the " + player.rank + " of " + player.suit);
System.out.println("Player 2 played the " + player2.rank + " of " + player2.suit);
if (player.getCard() > player2.getCard()){
System.out.println("You win!");
}
else if (player.getCard() < player2.getCard()){
System.out.println("Player 2 wins!");
}
else if (player.getCard() == player2.getCard()){
if(player.getSuit() > player2.getSuit()){
System.out.println("You win!");
}
else if(player.getSuit() < player2.getSuit()){
System.out.println("Player 2 wins!");
}
else{
System.out.println("There was a draw.");
}
}
}
}
Is there a way I could make it so it will say "Jack" and "Queen" without getting an error?
You're not able to pass non-numeric text into a parseInt() method call because it's not actually a number. Another way you could do it would be to try this instead:
String suit;
String rank;
int a;
int b;
int getCard;
int getSuit;
public Card(){
String [] xSuit = {"Clubs","Diamonds","Hearts","Spades"};
// xRank array removed because I don't think you need it anymore.
a = ((int)(Math.random() * 4));
b = ((int)(Math.random() * 13) + 1);
suit = xSuit[a];
switch(b) {
case 1:
rank = "Ace";
break;
case 11:
rank = "Jack";
break;
case 12:
rank = "Queen";
break;
case 13:
rank = "King";
break;
default:
rank = Integer.toString(a);
break;
}
}
int getCard(){
return b; // this will probably be unnecessary now, you'd probably also want a better name for this numeric card value...
}
I'm very new to Java and I'm having trouble understanding how to shuffle an array (or my deck array). I've tried using the Random class, but it's not doing the thing for me. Anyway, here go the classes I've created:
CardGame
import java.util.Random;
public class CardGame {
public static void main(String[] args) {
// final int SPADES = 0, HEARTS = 1, DIAMONS = 2, CLUBS = 3;
final int ACE = 1, TWO = 2, THREE = 3, FOUR = 4, FIVE = 5, SIX = 6, SEVEN = 7, EIGHT = 8;
final int NINE = 9, TEN = 10, JACK = 11, QUEEN = 12, KING = 13;
Random rand = new Random();
int[][] deck = {
{ ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING },
player1.setHand(deck[i][randIndex]);
player2.setHand(deck[i][randIndex]);
player3.setHand(deck[i][randIndex]);
}
}
System.out.println(player1.getHand());
System.out.println(player2.getHand());
System.out.println(player3.getHand());
}
}
Player
public class Player {
final int MAX_HAND = 6;
private String playerName;
private int playerHand[] = new int[MAX_HAND];
public Player(String name) {
playerName = name;
}
public void setHand(int card) {
int currentLength = playerHand.length;
if (currentLength == MAX_HAND) {
return;
}
playerHand[currentLength] = card;
}
public String getHand() {
String cardN
case 8: cardNames += "Eight"; break;
case 9: cardNames += "Nine"; break;
case 10: cardNames += "Ten"; break;
case 11: cardNames += "Jack"; break;
case 12: cardNames += "Queen"; break;
case 13: cardNames += "King"; break;
}
if (i < playerHand.length - 2) {
cardNames += ", ";
}
}
return playerName + " has " + cardNames + " on his hand.";
}
}
The result is always:
Name1 has Ace, Two, Three, Four and Five on his hand. Name2 has Ace,
Two, Three, Four and Five on his hand. Name3 has Ace, Two, Three, Four
and Five on his hand.
What is it that I'm doing wrong to generate a random index for the inner array of deck?
Thank you.
Replace switch (i) with switch (playerHand[i]) in your getHand() method and also call nextInt() for every player not just once on each iteration.
Change setHand() into
int index = 0;
public void addCard(int card) {
if (index == MAX_HAND) {
return;
}
playerHand[index++] = card;
}
you need to call rand.nextInt after each time you set a card.
player1.setHand(deck[i][rand.nextInt(deck[i].length)]);
player2.setHand(deck[i][rand.nextInt(deck[i].length)]);
player3.setHand(deck[i][rand.nextInt(deck[i].length)]);