I've got an assignment in JAVA that is a card game like War. I have to set values for 1-13 to signify cards and pick them at random. I've declared my variables and set them to have a max value, but I still get values that are well over 13. I've used Math.random() many times before with no problems whatsoever. I haven't condensed the code and probably some bloated lines and other lines just need not be there but it shouldn't affect my Math.random() numbers. Any help is greatly appreciated!!
class Card {
public int cardNum;
public int cardSuit1;
public int cardSuit2;
public final int CARDS_IN_SUIT;
public Card()
{
this.CARDS_IN_SUIT = 13;
this.cardSuit1 = 4;
this.cardSuit2 =4;
}
public void setCardNum1(int card)
{
cardNum = card;
}
public int getCardNum1()
{
if ((cardNum > 13) || (cardNum < 1))
{
cardNum = (((int) (Math.random() * 100 % CARDS_IN_SUIT + 1)));
}
return cardNum;
}
public void setCardNum2(int card)
{
cardNum = card;
}
public int getCardNum2()
{
cardNum = (((int) (Math.random() * 100 % CARDS_IN_SUIT + 1)));
return cardNum;
}
public int setCardSuit1()
{
cardSuit1 = ((int) (Math.random() * 100 % cardSuit1 + 1));
switch (cardSuit1)
{
case 1:
Integer.parseInt("Spades");
break;
case 2:
Integer.parseInt("Hearts");
break;
case 3:
Integer.parseInt("Diamonds");
break;
case 4:
Integer.parseInt("Clubs");
break;
}
return cardSuit1;
}
public int getCardSuit1()
{
return cardSuit1;
}
public int setCardSuit2()
{
cardSuit2 = ((int) (Math.random() * 100 % cardSuit2 + 1));
if (cardSuit1 == cardSuit2)
{
cardSuit2 = ((int) (Math.random() * 100 % cardSuit2 + 1));
}
else
{
return cardSuit2;
}
switch (cardSuit2)
{
case 1:
Integer.parseInt("Spades");
break;
case 2:
Integer.parseInt("Hearts");
break;
case 3:
Integer.parseInt("Diamonds");
break;
case 4:
Integer.parseInt("Clubs");
break;
}
return cardSuit2;
}
public int getCardSuit2()
{
return cardSuit2;
}
}
/////////////////////////////////////////////////////////////////////////
import javax.swing.JOptionPane;
class DisplayCard
{
public static void main(String[] args)
{
final int CARDS_IN_SUIT = 13;
final int cardNum = (((int) (Math.random() * 100 % CARDS_IN_SUIT + 1)));
Card firstCard = new Card();
Card secondCard = new Card();
firstCard.setCardNum1(cardNum);
firstCard.getCardSuit1();
secondCard.setCardNum2(cardNum);
secondCard.getCardSuit2();
JOptionPane.showMessageDialog(null, "Your first card is the " +
firstCard.getCardNum1() + firstCard.getCardSuit1() + " and the second"
+ " card for your hand is " +
secondCard.getCardNum2() + secondCard.getCardSuit2());
}
}
Aucun commentaire:
Enregistrer un commentaire