Member Avatar for Member #1236512

Hi, I am new to Java but familiar with python, I need to convert my code from python to Java can anyone help me? Much appreciated!

import random


suits = ['C', 'S', 'H', 'D']
val = list(range(1,14))


class Card:
    def __init__(self, suits, val):
        self.suit = suits
        self.value = val

    def show(self):
        print("{} of {}". format(self.value, self.suit))


class Deck:
    def __init__(self):
        self.cards = []
        self.build()

    def build(self):
        for s in ['C', 'S', 'H', 'D']:
            for v in list(range(1,14)):
                self.cards.append(Card(s, v))

    def show(self):
        for c in self.cards:
            c.show()

    def shuffle(self):
        for i in range(len(self.cards) - 1, 0, -1):
            r = random.randint(0, i)
            self.cards[i], self.cards[r] = self.cards[r], self.cards[i]

    def drawCard(self):
        if len(self.cards) > 0:
            return self.cards.pop(0)
        else:
            return None

    def returnCard(self, card):
        self.cards.append(card)


# %%

def game():
    deck = Deck()
    deck.shuffle()
    matches = [False for i in range(13)]
    table = [[] for i in range(13)]

    win = 0

    while len(deck.cards) > 0 and win == 0:
        for i in range(1,14):
            if all(matches) == True:
                win = 1
                break
            else:
                if len(deck.cards) > 0:
                    if matches[i-1] == False:
                        card = deck.drawCard()
                        if card.value == i:
                            matches[i-1] = True
                            for j in table[i-1]:
                                deck.returnCard(j)
                            table[i-1].clear()
                        table[i-1].append(card)
                    else:
                        continue
    return(win)

#%%
wins = 0 
n = 100000
for i in range(n):
    wins += game()

winrate = wins/n
print(winrate)

Dani AI

Generated

A practical way to approach this port is to treat it as a small design exercise rather than a mechanical transcription. First define the domain model (Card, Deck, game runner) and the operations each type must support. That follows 's suggestion to list classes and members, while also addressing 's concern about Python list semantics and 's suggestion to document intent with stubs/Javadoc before filling in implementations.

Prefer clear Java types: an enum for suits, a small immutable Card (a record on modern JDKs or a final class otherwise), and a collection that supports O(1) front/removal. Example (Java 16+ for records; use a final class if targeting older JDKs):

public enum Suit { C, S, H, D }

public record Card(Suit suit, int value) {
  @Override public String toString() { return value + " of " + suit; }
}

For the deck, build the list, call Collections.shuffle(list) to randomize, then use an ArrayDeque for queue semantics (shuffle works on List; ArrayDeque gives O(1) draw/return):

List<Card> list = new ArrayList<>();
// populate list with Suit.values() and values 1..13
Collections.shuffle(list);
Deque<Card> deck = new ArrayDeque<>(list);

public Card draw() { return deck.pollFirst(); }    // null when empty
public void returnCard(Card c) { if (c!=null) deck.addLast(c); }

Key gotchas and tips: avoid ArrayList.remove(0) (O(n)) — use ArrayDeque or LinkedList for queue ops; be explicit about 0-based indexing when converting loops; prefer Collections.shuffle (well-tested) instead of hand-rolled swaps unless implementing Fisher–Yates intentionally; use Optional or null-checks for empty draws; if running many simulations, use ThreadLocalRandom/Random appropriately and consider performance of object allocation. If targeting long-term maintenance, add equals/hashCode/toString (or rely on record-generated ones), small unit tests for one simulation, then scale up.

Recommended Answers

All 4 Replies

What you have is fairly basic. I would suggest making a list of each class the fields/properties and functions, with descriptions and build the the java versions from that. Google becomes your friend here. Use it to look up code to accomplish what needs to be done(i.e. shuffle algorithm).
The main advantage of this is, you learn about java as you work on this and become more grounded in it.

The one thing in this that could trip you up is that Python’s [] do not translate to Java’s [] arrays. Java arrays do not support list-like operations such as pop or append. Java’s Deque (double ended queue) class should provide all you need when the code uses more than just an indexed access.

Actually, you could construct a script that produced a Java class for each Python class, including method stubs, and then placed the Python implementation of the function within the Javadoc.
In reality, this is probably rather simple to do in Python.
I worked for a business that ported a large Smalltalk (similar to Python) system to Java, and this is precisely what they did. Filling out the techniques was tedious but necessary since it forced you to think about what was going on. I doubt that a brute-force approach would produce good code.

A lot depends on whether you are doing a simple conversion or producing a Java equivalent program. Eg simple conversion would just use classes where a more natural Java version would use enums for Suit and Value, and a record for Card.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.