Let's start, 3 classes (Card,Start,Deckofcards)
1º Card:
public class Card {
private String type;
private int value;
private String number;
public Card(String number,String type,int value) {
this.type=type;
this.value=value;
this.number=number;
}
public String gettype() {
return type;
}
public String getNumber() {
return number;
}
public int getValue() {
return value;
}
#Override
public String toString() {
return getNumber() + " de " + gettype() + " --> VALUE " + getValue() ;
}
}
2º Start
public class Start {
public static void main(String[] args) {
Deckofcards deckofcards = new Deckofcards();
Card c = deckofcards.newCard();
String s =c.toString();
System.out.println(s);
Card c2 = deckofcards.newCard();
String s2 =c2.toString();
System.out.println(s2);
}
}
Then, the problem is here
Deckofcards:
public class Deckofcards {
private Card CardsR[];
private final Card[] Cards = {
new Card("A","heart",1),
new Card("2","heart",2),
new Card("3","heart",3),
new Card("4","heart",4),
new Card("5","heart",5),
new Card("6","heart",6),
new Card("7","heart",7),
new Card("8","heart",8),
new Card("9","heart",9),
new Card("10","heart",10),
new Card("J","heart",10),
new Card("Q","heart",10),
new Card("K","heart",10),
new Card("As","Diamond",1),
new Card("2","Diamond",2),
new Card("3","Diamond",3),
new Card("4","Diamond",4),
new Card("5","Diamond",5),
new Card("6","Diamond",6),
new Card("7","Diamond",7),
new Card("8","Diamond",8),
new Card("9","Diamond",9),
new Card("10","Diamond",10),
new Card("J","Diamond",10),
new Card("Q","Diamond",10),
new Card("K","Diamond",10),
new Card("A","clover",1),
new Card("2","clover",2),
new Card("3","clover",3),
new Card("4","clover",4),
new Card("5","clover",5),
new Card("6","clover",6),
new Card("7","clover",7),
new Card("8","clover",8),
new Card("9","clover",9),
new Card("10","clover",10),
new Card("J","clover",10),
new Card("Q","clover",10),
new Card("K","clover",10),
new Card("A","Spades",1),
new Card("2","Spades",2),
new Card("3","Spades",3),
new Card("4","Spades",4),
new Card("5","Spades",5),
new Card("6","Spades",6),
new Card("7","Spades",7),
new Card("8","Spades",8),
new Card("9","Spades",9),
new Card("10","Spades",10),
new Card("J","Spades",10),
new Card("Q","Spades",10),
new Card("K","Spades",10),
};
//Sorry if the translation its not correct, this is only a little part of a
//big code.
public Deckofcards() {
Collections.shuffle(Arrays.asList(Cards)); //SHUFFLE
CardsR=Cards.clone(); //COPY
}
public Card newCard(){
boolean while1 = true;
Card take=null;
for(int i = 0; i < CardsR.length; i++){
while(while1){
if(CardsR[i]!=null){
take=Cards[i];
//CardsR[i]=null;
while1=false;
}
}
}
return take;
}
}
Let's explain.
I have an array of cards, that i mix.
OK. ALL CORRECT
Then i call to recive a card (Class: start).
OK. ALL CORRECT
--- THEN ---
when i call another time, the card returns the same value...
I tried to set a null... but then it starts a infinite loop by no reason?.
Any possible solution?
Thanks
when i call another time, the card returns the same value
Because
for(int i = 0; i < CardsR.length; i++){ // i = 0
while(while1){ // true
if(CardsR[i]!=null){ // true
take=Cards[i]; //
while1=false; // so no more while loop execution
// first card will always returned
I tried to set a null... but then it starts a infinite loop by no
reason?
during first call Card c = deckofcards.newCard(); the CardsR[0] was set to null so during second call Card c2 = deckofcards.newCard(); your if condition if(CardsR[i]!=null) will never be executed and now you are stuck in an infinite while loop
boolean while1 = true;
Card take=null;
for(int i = 0; i < CardsR.length; i++){
while(while1){
if(CardsR[i]!=null){
take=Cards[i];
//CardsR[i]=null;
while1=false;
}
}
}
Solution : simply you can use Random instance to pick and return random cards from array .
How to randomly pick an element from an array
You're not really doing anything with the shuffled list of cards; the instance is essentially transient and therefore garbage-collected. Note that shuffling the list you created out of the array, does not shuffle the array. Instead, you could do this:
List<Card> cardList = Arrays.asList(Cards);
Collections.shuffle(cardList);
CardsR = cardList.toArray(new Card[cardList.size()]);
Your newCard method doesn't need to be this complicated. I assume you just want to return a card from the shuffled array. One way to do this is to maintain an index of the last card taken; you can initialize it to -1 in your constructor. In newCard, you will increment this index and return the card at that index as long as you are not out of bounds. If you are, you might want to print a message saying there are no cards left (for example).
Some other pointers:
Make sure you follow Java naming-conventions; field and variable names should not be capitalized.
Consider using a List<Card> of cards instead of an array; that way you can simply shuffle instead of needlessly converting back and forth between an array and a list.
The value of take will always be the first card in the array.
The while loop never terminates when you set the value equal to null because while2 is only set to false when a non-null entry is found. Once a null is found, then nothing happens and the while loop runs forever because there is no way for while2 to be set to false.
A break statement should do the trick here
public Card newCard(){
Card take=null;
for(int i = 0; i < CardsR.length; i++){
if(CardsR[i]!=null){
take=Cards[i];
CardsR[i]=null;
break;
}
}
}
return take;
}
A break statement will exit whatever loop it is in.
Alternatively, you can use a List<Card> instead of an array, with which you can remove entries from your shuffled list and return them, removing the need to set and check for null.
private List<Card> cardList;
public Deckofcards() {
cardList = Collections.shuffle(Arrays.asList(Cards)); //SHUFFLE
}
public Card newCard(){
if(!cardList.isEmpty()){
return cardList.remove(0);
}
return null;
}
I posted a question earlier pertaining to the same problem but my question is completely different this time so please hear me out before you mark this as a duplicate or downvote it.
So for my assignment I was supposed to create a class called "Card" that would represent a standard playing card with a suit and face represented by numbers(1-4 for suit, 1-13 for face), and also constructors to initialize the cards, and mutator and accessor functions to change a card object and output its string representation(for example, King of Hearts). Then I had to create another class called DeckOfCards that represents a deck of 52 cards, storing 52 Card objects. This class has a constructor to the initialize a deck with the standard 52 cards, and member functions to shuffle the deck, deal a card, and print all the cards in the deck. My problem is trying to get the constructor for this DeckOfCards class to work. Here's the code for the entire class and my particular problem is with the constructor method:
public class DeckOfCards
{
/*Class that stores 52 objects of the Cards class. Include methods to shuffle the deck,
* deal a card, and report the number of cards left in the deck, and print all the cards in
the deck.*/
private Card[] deck = new Card[52];
private int count = 52, j = 0;
public DeckOfCards()/*Constructor initializes the deck with 52 cards*/
{
int i = 0;
for (int suit = 0;suit < 4;suit++)
{
for (int face = 0;face < 13;face++)
{
deck[i] = Card(suit, face);
i++;
}
}
}
public String toStringDeck()//Prints all the cards in the deck
{
String deckPrint = "";
for (int i = 0; i < 52;i++)
{
deckPrint += deck[i].toString() + "\n";
}
return deckPrint;
}
public void shuffle()//Shuffles the deck
{
Random generator = new Random();
int rand1, rand2;
Card temp;
for (int i = 0;i < 100;i++)
{
rand1 = generator.nextInt(52);
rand2 = generator.nextInt(52);
temp = deck[rand1];
deck[rand1] = deck[rand2];
deck[rand2] = temp;
}
}
public void deal()/*Deals a card from the deck and prints it as its dealt. Reports the number
of cards remaining in the deck.*/
{
String deal;
if (j < 52)
{
deal = deck[j].toString();
j++;
System.out.println(deal);
count--;
System.out.println("There are " + count + " cards remaining in the deck.");
}
else
{
System.out.println("There are no cards remaining in the deck.");
}
}
}
When I try to compile this, I get the error: "Cannot find symbol - method Card(int,int)."
I can't understand why, in the constructor, I'm not able to create a Card object and initialize it here. Please let me know if I need to give more details. Thanks.
You forgot the new keyword. Change
deck[i] = Card(suit, face);
to
deck[i] = new Card(suit, face);
& make sure that you have defined a 2-args constructor in your Card class.
I have created two classes, one called "Bucket", and the other called "Player".
In "Bucket", I have a constructor method that creates a virtual bucket (i.e. small array) that contains three values - 1, 1, and 1. As well, I created a method to get the bucket array.
In the "Player" class, I have created a method that uses a larger array (I have called this larger array "ArrayOfBuckets"), which uses a loop to store a new bucket at each index value, up until a certain point (when i>NumberSticks). However, when I try to set
ArrayofBuckets[i] = bucketInstance.getBucket();
I get an error from Eclipse, saying that "Type mismatch: cannot convert from Bucket to int". I have spent an hour trying to solve this, to no avail. Any help would be really nice. Thanks a lot, and here is all the code that is used:
The Player Class:
import java.util.Scanner;
public class Player {
Scanner scan = new Scanner(System.in);
public String name;
private int pType;
private int[] ArrayOfBuckets;
public Player(String tempName)
{
this.name = tempName; //this. is unneccessary
}
public void ArrayOfBuckets(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
ArrayOfBuckets = new int[NumberSticks];
int i = 0;
while(i<NumberSticks)
{
Bucket bucketInstance = new Bucket();
ArrayOfBuckets[i] = bucketInstance.getBucket();//new Bucket(); //ADD THIS
i++;
}
}
and the Bucket Class:
import java.util.Random;
public class Bucket {
// private int[][] largeArray = null; //WTF DO I DO HERE
private int AIChoiceStick;
private int[] bucket;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public Bucket()
{
bucket = new int[3];
bucket[0] = 1;
bucket[1] = 1;
bucket[2] = 1;
public int[] getBucket()
{
return bucket;
}
You're speaking about a two-dimensional array.
private int[][] ArrayOfBuckets;
Your ArrayOfBuckets (should be just buckets according to naming conventions) is an array of arrays, so it gets two sets of square brackets.
Then the initialization:
ArrayOfBuckets = new int[NumberSticks][3];
By the way, if you want to have room for 50 elements in an array, then initialize it new int[50] so it will have indexes 0 through 49.
I'm making a little card deck program that uses an ArrayList for the deck. One of the limitations set upon me is that the method in which I "deal" the cards must be an Arraylist type. The problem I'm running into is that I don't know how to return just a specific index value from the ArrayList. See below.
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
So how can I return the first item of the List and still have it be the correct type? The rest of the code doesn't matter, just the Method type and return statement.
EDIT: As requested
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
If you cannot change the signature and it is mandatory to return an arraylist, then you can create an arraylist with just one element and return it. Something like this:
ArrayList returnList = new ArrayList();
returnList.add(al.get(0));
return returnList;
Does not look great to me :-(
In your specific case, al is an ArrayList<String>. That means al.get(...) returns a String. However, your method is declared as returning an ArrayList, which is not a String. You will either need to change your method return type to String, or you will need to construct a new ArrayList and add your single string to it and return that.
Your declared return type needs to match the object you are returning. So for example:
ArrayList<String> al = ...;
String getSingleItem (int index) {
return al.get(index);
}
ArrayList<String> getSingleItemAsArrayList (int index) {
ArrayList<String> single = new ArrayList<String>();
single.add(al.get(index));
return single;
}
ArrayList<String> getItems () {
return al;
}
By the way, it's generally better to specify the type parameter to ArrayList, e.g. ArrayList<Whatever>, as this can save you a lot of casting things around / unchecked conversions and will give you compile-time checking of types.
Is there a reason that you have to return an ArrayList? Essentially, you are trying to create a method that takes a deck, picks a card, and then returns a deck. You could try and use the subList method someone mentioned above. You could create a new ArrayList containing only the card you want, but that's not very efficient. Or, if your goal is to actually return the whole deck, but with the correct card on top (aka in the first position of the ArrayList), there's lots of info about rearranging values in an ArrayList online.
EDIT: Based on your full code, it looks like the goal is to flip the first card face up. You should do that (not gonna do your homework for you!) and then return the ArrayList that the method took in. IRL, imagine handing someone a deck, they flip the first card face up, then hand the deck back to you.
//ADDING AND deleting employees
//Displaying employee list
public class EployeeDB {
static ArrayList e = new ArrayList<>();
public static boolean addEmployee(Employee e1) {
e.add(e1);
System.out.println("Employee added");
return true;
}
public static boolean deleteEmployee(int ecode) {
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
e.remove(i);
break;
}
}
if (temp == 1)
System.out.println("Emp deleted");
else
System.out.println("Deletion unsuccessful, check ecode again");
return true;
}
public static String showPaySlip(int ecode) {
double salary = 0;
int temp = 0;
for (int i = 0; i < e.size(); i++) {
if (e.get(i).getID() == ecode) {
temp = temp + 1;
salary = e.get(i).getSalary();
break;
}
}
if (temp == 1)
return "Salary is" + salary;
else
return "No employye found with the specified ecode";
}
public static ArrayList<Employee> listAll() {
return e;
}
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setID(20);
e1.setName("sai");
e1.setSalary(150.00);
addEmployee(e1);
Employee e2 = new Employee();
e2.setID(30);
e2.setName("kumar");
e2.setSalary(1500.00);
addEmployee(e2);
deleteEmployee(30);
System.out.println(showPaySlip(30));
for (int i = 0; i < e.size(); i++)
System.out.println(
listAll().get(i).getID() + " " + listAll().get(i).getName() + " " + listAll().get(i).getSalary());
}
}
I am trying to make a poker game through java.
The first thing I wanted to do is distribute 5 cards using arrays. I have done the distribution part, but how can I prevent the same cards being distributed twice. In other words, how can I check if an array already contains an element. I want it to be able to detect if the element already exists in an array, and if it does, I want to be able to change just that card that has been given out twice, help would be much appreciated.
My codes down below,
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Poker
{
public final static String[] numbers = {"❤","♠","♦","♣"};
public final static String[] sign = {"1","2","3","4","5","6","7","8","10","J","Q","K","A"};
private String[] hand = {"","","","",""};
private boolean found;
private Random random;
public Poker()
{
found = false;
String hand[] = {"","","","",""};
int tokens = 10;
Scanner in = new Scanner(System.in);
random = new Random();
}
public void handOut()
{
for (int i = 0; i < 5; i++)
{
int numberRandom = random.nextInt(numbers.length);
int signRandom = random.nextInt(sign.length);
String pickedNumber = numbers[numberRandom];
String pickedSign = sign[signRandom];
String combinedSigns = pickedSign + pickedNumber;
hand[i] = combinedSigns;
System.out.print(hand[i] + " ");
}
System.out.println("\n");
}
}
Your choice of terminology is ... err ... interesting :-)
The card value is a "face value", not a sign. And whether it's hearts or diamonds or so on, that's its "suit" rather than its number.
But, on to the question. I believe the best way to do this is to construct an entire 52-card deck out of your facevalue and suit arrays and then use a Fisher Yates shuffle to distribute cards.
This is a nifty way to randomly choose elements from an array without duplicates. The beauty is that the items in the array don't actually need to be shuffled up front. Details on how it works can be found here.
If you can use the collections framework as opposed to an array, create a Stack and populate it with all the 52 cards. then call Collections.shuffle() on it.
finally set hand[i]=(deck name).pop()
Once a card is popped from the stack it will be removed from the deck so it can't be dealt again.
What you want to do is break your code into different methods. You should have a method for generating one card, a method for checking whether or not a card is in the hand, and a method to distribute cards to the hand.
public String generateCard() {
int numberRandom = random.nextInt(numbers.length);
int signRandom = random.nextInt(sign.length);
String pickedNumber = numbers[numberRandom];
String pickedSign = sign[signRandom];
return pickedSign + pickedNumber;
}
public static boolean cardIsInHand(String card) {
for(int i = 0; i < 5; i++) {
if(hand[i] != null && hand[i].contains(card)) {
return true;
}
}
return false;
}
public static void handout() {
for (int i = 0; i < 5; i++) {
String card = generateCard();
while(cardIsInHand(card)) {
card = generateCard();
}
hand[i] = card;
}
}