Skip to content
Snippets Groups Projects

Refactored code in DeckOfCards class with import Random, Created test class...

Merged Steven Ha requested to merge master into main
2 files
+ 58
5
Compare changes
  • Side-by-side
  • Inline
Files
2
@@ -3,13 +3,15 @@ package edu.ntnu.idatt2003;
@@ -3,13 +3,15 @@ package edu.ntnu.idatt2003;
import java.util.Collections;
import java.util.Collections;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.List;
import java.util.List;
 
import java.util.Random;
/**
/**
* En kortstokk bestående av 52 kort.
* En kortstokk bestående av 52 kort.
 
*/
*/
public class DeckOfCards {
public class DeckOfCards {
private final List<PlayingCard> cards = new ArrayList<>();
private final List<PlayingCard> cards = new ArrayList<>();
private final Random random = new Random();
public DeckOfCards() {
public DeckOfCards() {
char[] suits = { 'S', 'H', 'D', 'C' };
char[] suits = { 'S', 'H', 'D', 'C' };
@@ -19,10 +21,10 @@ public class DeckOfCards {
@@ -19,10 +21,10 @@ public class DeckOfCards {
}
}
}
}
}
}
/**
/**
* Blander kortene i kortstokken.
* Blander kortene i kortstokken.
*/
*/
 
public void shuffle() {
public void shuffle() {
Collections.shuffle(cards);
Collections.shuffle(cards);
}
}
@@ -35,17 +37,23 @@ public class DeckOfCards {
@@ -35,17 +37,23 @@ public class DeckOfCards {
* @throws IllegalArgumentException hvis det ikke er nok kort til å dele ut ønsket antall.
* @throws IllegalArgumentException hvis det ikke er nok kort til å dele ut ønsket antall.
*/
*/
public List<PlayingCard> dealHand(int n) {
public List<PlayingCard> dealHand(int n) {
if (n > cards.size()) {
if (n < 1 || n > cards.size()) {
throw new IllegalArgumentException("Not enough cards in the deck to deal the hand.");
throw new IllegalArgumentException("Invalid number of cards to deal.");
}
}
List<PlayingCard> hand = new ArrayList<>();
List<PlayingCard> hand = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int i = 0; i < n; i++) {
hand.add(cards.remove(cards.size() - 1));
int index = random.nextInt(cards.size());
 
hand.add(cards.remove(index));
}
}
return hand;
return hand;
}
}
 
/**
 
* Returnerer antall kort som er igjen i kortstokken.
 
* @return antall kort som er igjen i kortstokken.
 
*/
 
public int cardsLeft() {
public int cardsLeft() {
return cards.size();
return cards.size();
}
}
Loading