how to get the enum values one by one using a loop - java

i'm trying to get the enum values one by one using a for loop without the need to specify all possible values like i'm doing in the code Value.As be replaced by something like Value.values()but when i try this it doesn't work for me :
public class Deck {
private LinkedList<Card> cardList;
public Deck(int nbBox) {
this.cardList = new LinkedList<Card>();
for (int i = 0; i < nbBox; i++) {
for (int j = 0; j < 52; j++) {
cardList.add(new Card(Value.AS, Color.CLUB));
}
}
}
public Card draw() {
return null; // not done yet
}
#Override
public String toString() {
return "Here is the deck : " +cardList;
}
public LinkedList<Card> getCardList() {
return cardList;
}
public void setCardList(LinkedList<Card> cardList) {
this.cardList = cardList;
}
}

You could use a for-each loop on the values(). This reads as for each suit, for each value add a new card with the suit and value to the List. Also, you could use diamond operator <> like,
public Deck(int nbBox) {
this.cardList = new LinkedList<>(); // <-- diamond operator
for (int i = 0; i < nbBox; i++) {
for (Suit suit : Suit.values()) {
for (Value value : Value.values()) {
cardList.add(new Card(suit, value));
}
}
}
}

Try this:
enum Mobile {
Samsung(400), Nokia(250),Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
public class EnumDemo {
public static void main(String args[]) {
System.out.println("CellPhone List:");
for(Mobile m : Mobile.values()) {
System.out.println(m + " costs " + m.showPrice() + " dollars");
}
Mobile ret = Mobile.Samsung;
System.out.println("The ordinal is = " + ret.ordinal());
System.out.println("MobileName = " + ret.name());
}
}
The output will be:
CellPhone List:
Samsung costs 400 dollars
Nokia costs 250 dollars
Motorola costs 325 dollars
The ordinal is = 0
MobileName = Samsung

Related

Card Game Adding cards to a set of "hands" --Java

I am trying to make a basic outline for a card game, I have the deck created, a method created for dealing a random card but I am having difficulty for adding the card into the actual hand. The issue is in the Game class with the getCard() method. I do not know the correct way to do this, since my idea did not work.
Class to create the deck:
import java.util.Random;
public class Deck<E> {
//create a new linked list for Deck
LinkedPositionalList deck = new LinkedPositionalList();
public Deck(){
for (int i = 0; i < 4; i++){
for(int j = 2; j< 14; j++){
Card card = new Card(i,j);
deck.addLast(card); //add to linked list
}
}
}
public Card card(){
Random rand = new Random();
int position = rand.nextInt(52);//create random number 0-52
int counter = 0;
Iterator<Card> iter = this.deck.iterator();
while(counter <= position){
Card card = iter.next();
if(counter == position){
iter.remove();
return card;
}
counter++;
}
return null;
}
}
Class to create the card:
public class Card<E> {
public final static int CLUBS = 0,
SPADES = 1,
DIAMONDS = 2,
HEARTS = 3;
private final static String [] suitNames = {"CLUBS", "SPADES", "DIAMONDS", "HEARTS"};
// Special cards
private int JACK_VALUE = 11;
private int QUEEN_VALUE = 12;
private int KING_VALUE = 13;
private int ACE_VALUE = 14;
// The card
private int suit = 0; // Suit of the card
private int value = 2; // Value of the card
public int getSuit() {
return this.suit;
}
public int getValue() {
return this.value;
}
public Card(int suit, int value ){
this.suit = suit;
this.value = value;
}
public String suitToString() {
return suitNames[ suit ];
}
public String valueToString() {
if (value == ACE_VALUE) {
return "ACE";
} else if (value == JACK_VALUE) {
return "JACK";
} else if (value == QUEEN_VALUE) {
return "QUEEN";
} else if (value == KING_VALUE) {
return "KING";
} else if ( value > 0 ) {
return String.valueOf(value);
}
return "";
}
public String shortValueToString() {
if (value == ACE_VALUE) {
return " A";
} else if (value == JACK_VALUE) {
return " J";
} else if (value == QUEEN_VALUE) {
return " Q";
} else if (value == KING_VALUE) {
return " K";
} else if ( value > 0 ) {
return String.format("%2d",value);
}
return "";
}
public String toString() {
return valueToString() + " of " + suitToString();
}
public String toShortString() {
return shortValueToString() + suitToString().substring(0,1);
}
public boolean equalTo(Card c ) {
if ( c.getSuit() != this.getSuit()) return false;
if ( c.getValue() != this.getValue()) return false;
return true;
}
}
Class to create the hand:
public class CardHand<E> {
LinkedPositionalList<E> hand = new LinkedPositionalList();
//TODO: create method to order hand
}
Class to initialize the game:
public class Game{
int players;
int maxCardsInHand;
int decks;
CardHand[] hand;
Card card;
Deck deck;
//constructor
public Game(int player, int max, int numDecks){
players = player;
maxCardsInHand = max;
decks = numDecks;
this.hand = new CardHand[player];
for(int index = 0; index < hand.length; index++){
this.hand[index] = new CardHand();
}
}
public void getCard(){
System.out.println("You got this far...");
card = deck.card();
for(int index = 0; index < hand.length; index++){ //to add to each players hands
hand[index] = card; //issues with this part
}
//TODO: ordered correctly by suit AND value
}
Given that the call iter.remove(); works, your deck gets smaller and smaller each time you call the card() method. Yet you assume you can iterate thru a full deck:
rand.nextInt(52);
Instead, iterate only over the cards you have left:
rand.nextInt(this.deck.size());
If there is no size() or length() method for the list object, decrease a counter each time card() is called:
rand.nextInt(cardsInDeck++);

Any advice on how to fix this Stack Overflow error? Java

While developing a simple auto generating game of war in my free time, I ran into a "StackOverFlow" error.
Here is my Deck class where the error occurs:
It occurs in my compare() method. Any insight as to what I can do to avoid this error is accepted as I am struggling to understand what can be done to fix this and have little knowledge as to what this error even means besides my class doesn't have recursion done well. Thanks!
import java.util.*;
import java.math.*;
public class Deck
{
private int num = 0;
private int cardnum2 = 0;
private int cardnum = 0;
private int decrease = 0;
private int rnd = 0;
private int winner = 0;
private String suit = " ";
private int suitNum = 0;
private int val = 1;
private String name = "";
private ArrayList<Card> Deck = new ArrayList<Card>();
private Card[] cardCheck = new Card[51];
private ArrayList<Card> play1 = new ArrayList<Card>();
private ArrayList<Card> play2 = new ArrayList<Card>();
public Deck()
{
createDeck();
}
public void createDeck()
{
for(int i = 0; i < 4; i++)
{
val = 1;
suit = " ";
name = " ";
suitNum++;
System.out.println();
System.out.println();
for(int z = 0; z < 13; z++)
{
if(suitNum == 1)
{
suit = "Hearts";
}
if(suitNum == 2)
{
suit = "Diamonds";
}
if(suitNum == 3)
{
suit = "Spades";
}
if(suitNum == 4)
{
suit = "Clubs";
}
if(val == 1)
{
name = "Ace";
}
else if(val == 11)
{
name = "Jack";
}
else if(val == 12)
{
name = "Queen";
}
else if(val == 13)
{
name = "King";
}
else {
name = "";
}
Card myCards = new Card(val, suit, name);
Deck.add(myCards);
System.out.print(myCards + " ");
val++;
}
}
}
public void Deal()
{
int size = 52 / 2;
for(int i = 0; i < size; i++)
{
Random();
for(int z = 0; z < cardCheck.length; z++)
{
if(cardCheck[i] == null)
{
cardCheck[i] = Deck.get(rnd);
play1.add(cardCheck[i]);
System.out.println(play1);
}
else
{
Random();
}
}
}
System.out.println();
System.out.println();
for(int i = 0; i < size; i++){
Deck.remove(play1.get(i));
}
for(int i = 0; i < size; i++){
play2.add(Deck.get(i));
}
for(int i = 0; i < size; i++)
{
System.out.println(play2.get(i));
}
}
public void Random()
{
rnd = (int)(Math.random() * 52) - decrease;
}
public void flip()
{
if(play1.indexOf(cardnum) >= play1.size() || play2.indexOf(cardnum2) >= play2.size())
{
cardnum = (int)(Math.random() * play1.size());
System.out.println(play1.get(cardnum));
cardnum2 = (int)(Math.random() * play2.size());
System.out.println(play2.get(cardnum2));
}
}
public void compare()
{
System.out.println("War!!!\n");
if(play1.get(cardnum).getNum() > play2.get(cardnum2).getNum())
{
System.out.println();
winner = 1;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play1.add(play2.get(cardnum2));
play2.remove(cardnum2);
System.out.println("Player 1 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() < play2.get(cardnum2).getNum())
{
System.out.println();
winner = 2;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play2.add(play1.get(cardnum));
play1.remove(cardnum);
System.out.println("Player 2 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() == play2.get(cardnum2).getNum())
{
System.out.println();
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
System.out.println("War!!");
winner = 0;
flip();
flip();
flip();
compare();
System.out.println();
printDecks();
}
}
public void playW()
{
while(play1.size() > 0 || play2.size() > 0)
{
flip();
compare();
}
}
public void printDecks()
{
for(int i = 0; i < play1.size(); i++)
{
System.out.print(play1.get(i) + " ");
}
System.out.println();
for(int i = 0; i < play2.size(); i++)
{
System.out.print(play2.get(i) + " ");
}
System.out.println();
System.out.println("Player 1 has: " + play1.size() + " cards");
System.out.println("Player 2 has: " + play2.size() + " cards");
}
}
This is more a comment but it became too long.
There is a lot to say about this code. Use switch case instead of series of if. Or at least use if else. What is the point of a for loop if you use cases inside? What is the 'i' variable for if you then increment yourself a suitNum variable? Don't use capital letter for methods. Only classes. Why does Random edits a variable and returns void? It would be more logical that random() returns the result you want and this way you get free of the useless variable 'rnd'
There is a lot more to say but it is a good start. About your error, in short, a stack overflow means that your program is using too much memory. This is especially common in code that contains an infinite recursive loop. Here, the infinite recursion is due to the compare method called inside the compare method...
and have little knowledge as to what this error even means besides my class doesn't have recursion done well.
Yes, your code has recursion, and it's easy to find. You know that the problem is coming from within the compare method, and so all you have to do is look within that method for compare() and find out where you're having the method call itself.
The solution is not to call the method within itself, and why should it be doing this anyway?
You're having the issue partly because your class structure is broken. The Deck class is class that should represent the structure and behavior of a deck of cards, nothing more and nothing less, It should have methods like public void shuffle(), like public Card Deal(), and such. It should not have any code that directly interacts with the user, and this code should go elsewhere, perhaps in your driver or Game class, or even as separate class(es) entirely.
I'm guessing that you'll also want to have a Hand class, one that holds a player's hand, and perhaps inside of this class, have a compare method that compares the current Hand with another Hand, passed in as a parameter.
You'll also want a Game class should have a game-loop that controls play, that ends when there is a winner or a draw, that holds the Deck, that holds 1 or more Player objects...
e.g.,
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
public enum Value {
//....
}
public class Card {
private Suit suit;
private Value value;
// TODO: constructor, methods including equals, hashCode
}
public class Deck {
private List<Card> cards = new ArrayList<>();
public Card deal() {
return cards.remove(0);
}
public void shuffle() {
Collection.shuffle(cards);
}
//....
}
class Player {
// either use a List in each Player or create a class called hand
private List<Card> hand;
private int cash;
private String name;
private Game game;
// TODO: constructor
// TODO: methods including receiveCard(Card c), List<Card> showHand(),...
}
public class Game {
private Player p1;
private Player p2;
private Deck deck;
private int moneyPot;

recursive method not properly executing

I have a programming assignment for an introductory level Java class (the subset sum problem) - for some reason, my recursive method isn't executing properly (it just goes straight to the end of the method and prints out the sorted list). Any help would be appreciated - I'm a newbie and recursive functions are really confusing to me.
package programmingassignment3;
import java.io.*;
import java.util.*;
public class ProgrammingAssignment3 {
static int TARGET = 10;
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
public static void main(String[] args) {
populateSortSet();
sumInt(list);
recursiveSS(list);
}//main
public static void populateSortSet() {
try {
File f = new File("set0.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !list.contains(ele)) {
list.add(ele);
}//if
}//while
Collections.sort(list);
}//try
catch (IOException e) {
e.printStackTrace();
}//catch
}//populateSet
public static void recursiveSS(ArrayList<Integer> Alist) {
if (Alist.size() == SIZE) {
if (sumInt(Alist) == TARGET) {
System.out.println("The integers that equal " + TARGET + "are: " + Alist);
} //if==TARGET
}//if==SIZE
else {
for (int i = 0; i < SIZE; i++) {
ArrayList<Integer> list1 = new ArrayList<>(Alist);
ArrayList<Integer> list0 = new ArrayList<>(Alist);
list1.add(1);
list0.add(0);
if (sumInt(list0) < TARGET) {
recursiveSS(list0);
}//if
if (sumInt(list1) < TARGET) {
recursiveSS(list1);
}//if
}//for
}//else
System.out.println("echo" + Alist);
}//recursiveSS
public static int sumInt(ArrayList<Integer> Alist) {
int sum = 0;
for (int i = 0; i < SIZE - 1; i++) {
sum += Alist.get(i);
}//for
if (Alist.size() == TARGET) {
sum += Alist.get(Alist.size() - 1);
}//if
return sum;
}//sumInt
}//class
This thing that you do at class level:
static ArrayList<Integer> list = new ArrayList<>();
static int SIZE = list.size();
means that SIZE will be initiated to 0, and stay 0 (even if you add elements to the list.)
This means that the code inside the for-loop will be executed 0 times.
Try something like:
public class ProgrammingAssignment3 {
private static int initialSize;
//...
public static void populateSortSet() {
//populate the list
initialSize = list.size();
}
So you don't set the value of the size variable until the list is actually populated.
That being said, there a quite a few other strange things in your code, so I think you need to specify exactly what you are trying to solve here.
Here's how I'd do it. I hope it clarifies the stopping condition and the recursion. As you can see, static methods are not an issue:
import java.util.ArrayList;
import java.util.List;
/**
* Demo of recursion
* User: mduffy
* Date: 10/3/2014
* Time: 10:56 AM
* #link http://stackoverflow.com/questions/26179574/recursive-method-not-properly-executing?noredirect=1#comment41047653_26179574
*/
public class RecursionDemo {
public static void main(String[] args) {
List<Integer> values = new ArrayList<Integer>();
for (String arg : args) {
values.add(Integer.valueOf(arg));
}
System.out.println(String.format("input values : %s", values));
System.out.println(String.format("iterative sum: %d", getSumUsingIteration(values)));
System.out.println(String.format("recursive sum: %d", getSumUsingRecursion(values)));
}
public static int getSumUsingIteration(List<Integer> values) {
int sum = 0;
if (values != null) {
for (int value : values) {
sum += value;
}
}
return sum;
}
public static int getSumUsingRecursion(List<Integer> values) {
if ((values == null) || (values.size() == 0)) {
return 0;
} else {
if (values.size() == 1) { // This is the stopping condition
return values.get(0);
} else {
return values.get(0) + getSumUsingRecursion(values.subList(1, values.size())); // Here is recursion
}
}
}
}
Here is the case I used to test it:
input values : [1, 2, 3, 4, 5, 6]
iterative sum: 21
recursive sum: 21
Process finished with exit code 0
Thanks everyone. I really appreciate the help. I did figure out the problem and the solution is as follows (closing brace comments removed for the reading pleasure of #duffymo ):
public class ProgrammingAssignment3 {
static int TARGET = 6233;
static ArrayList<Integer> set = new ArrayList<>();
static int SIZE;
static int count = 0;
public static void populateSortSet() {
try {
File f = new File("set3.txt");
Scanner input = new Scanner(f);
while (input.hasNext()) {
int ele = input.nextInt();
if (ele < TARGET && !set.contains(ele)) {
set.add(ele);
}
}
Collections.sort(set);
SIZE = set.size();
System.out.println("The original sorted set: " + set + "\t subset sum = " + TARGET);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void recursiveSS(ArrayList<Integer> list) {
if (list.size() == SIZE) {
if (sumInt(list) == TARGET) {
System.out.print("The Bit subset is: " + list + "\t");
System.out.println("The subset is: " + getSubset(list));
count++;
}
}
else {
ArrayList<Integer> list1 = new ArrayList<>(list);//instantiate list1
ArrayList<Integer> list0 = new ArrayList<>(list);//instantiate list0
list1.add(1);
list0.add(0);
if (sumInt(list0) <= TARGET) {
recursiveSS(list0);
}
if (sumInt(list1) <= TARGET) {
recursiveSS(list1);
}
}
}
public static int sumInt(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
sum += set.get(i);
}
}
return sum;
}
public static ArrayList<Integer> getSubset(ArrayList<Integer> list) {
ArrayList<Integer> l = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == 1) {
l.add(set.get(i));
}
}
return l;
}
}

How to combine if statements in a loop

I have this class and in the printVotes method I had to do the if statement every time to print each votes. Is there any way to combine both the if statements. Could I print all the names of the candidates and the number of votes they got at the same time?
public class TestCandidate {
public static void main(String[] args)
{
Canidate[] canidate = new Canidate[5];
// create canidate
canidate[0] = new Canidate("John Smith", 5000);
canidate[1] = new Canidate("Mary Miller", 4000);
canidate[2] = new Canidate("Michael Duffy", 6000);
canidate[3] = new Canidate("Tim Robinson", 2500);
canidate[4] = new Canidate("Joe Ashtony", 1800);
printVotes(canidate) ;
}
public static void printVotes(Canidate [] List)
{
double max;
int index;
if (List.length != 0)
{
index = 0;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
}
if (List.length != 0)
{
index = 1;
for (int i = 1; i < List.length; i++)
{
}
System.out.println(List[index]);
return;
}
}
}
If you pass in a List<Candidate> candidates; and assuming that each candidate has a List<Integer> Votes:
List<Integer> votes= new ArrayList<Integer>() ;
for(Candidate c:candidates)
{
votes.add(c.GetVote()) ;
}
for(Integer v:votes)
{
System.out.println(v);
}
You could override the Candidate class's toString() method like so:
public String toString() {
return "Candidate Name: " + this.name + "\nVotes: " + this.votes;
}
Then your printVotes method would look something like this:
public static void printVotes(Candidate[] list) {
for(Candidate c : list) {
System.out.println(c);
}
}
As someone else mentioned, avoid using capital letters in variable names especially in cases where words such as List are used. List is a collection type and can be easily confused.

trouble with array lists

I am doing a project and instead of using an array, I figured an array list would be better. I know I need to declare the array list and its methods, but I am not too sure where to go from there. Any suggestions? Here's code...
public class Student {
private String name;
private int[] tests;
public Student() {
this("");
}
public Student(String nm) {
this(nm, 3);
}
public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}
public Student(String nm, int[] t) {
tests = new int[t.length];
}
public Student(Student s) {
this(s.name, s.tests);
}
public int getNumberOfTests() {
return tests.length;
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
public void setScore(int i, int score) {
tests[i - 1] = score;
}
public int getScore(int i) {
return tests[i - 1];
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}
I figured an array list would be better
Maybe. Maybe not. It depends. Does it look like you would get a benefit in using one based on the ArrayList API?
If your "list" never changes size, and you don't need to find things in it, then an array is just as good.
I know I need to declare the array list and its methods, but I am not
too sure where to go from there
You need to create a reference to an instance of an ArrayList. That's as simple as
List<Integer> myList = new ArrayList<Integer>();
in your class declaration. You don't need to "declare its methods". When you have a reference to an object, you can invoke its methods.
To use an ArrayList, you just need to declare and instantiate it:
// <SomeObject> tells Java what kind of things go in the ArrayList
ArrayList<SomeObject> aDescriptiveNameHere = new ArrayList<SomeObject>();
// This is also valid, since an ArrayList is also a List
List<SomeObject> list = new ArrayList<SomeObject>();
Then you can add things with the add() method:
// Please don't name your list "list"
list.add(new Thing(1));
list.add(new Thing(2));
You can get something by index (like you would with someArray[index]) as:
list.get(index);
// For example
Thing t = list.get(5);
You probably also need the size().
See the JavaDocs for more info.
All of the operations you're using are mirrored in the ArrayList API. One thing that's worth noting is that you cannot declare an ArrayList of primitive types, but for each of the primitive types there exists an Object that is the boxed version of the primative.
The boxed version of int is Integer, so you have
ArrayList<Integer> myList = new ArrayList<Integer>();
From there, you need to look up the methods you would need to use in order to manipulate the array. For example, if you want to add the number 42 to the end of the array, you would say
myList.add(42);
The ArrayList API is located here.
I think it could be better to use the stl vector instead make your own arrays
I tried to change the array to arraylist.
Reply if this doesn't compile correctly.
import java.util.ArrayList;
public class Student {
private String name;
// private int[] tests;
private ArrayList<Integer> tests;
public Student() {
this("");
}
public Student(String nm) {
// this(nm, 3);
name = nm;
}
/*
* public Student(String nm, int n) { name = nm; tests = new int[n]; for
* (int i = 0; i < tests.length; i++) { tests[i] = 0; } }
*/
/*
* public Student(String nm, int[] t) { tests = new int[t.length]; }
*/
public Student(Student s) {
this(s.name, s.tests);
}
public Student(String name2, ArrayList<Integer> tests2) {
name = name2;
tests = tests2;
}
public int getNumberOfTests() {
return tests.size();
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
// public void setScore(int i, int score) {
// tests[i - 1] = score;
public void setScore(int score) {
tests.add(score);
}
public int getScore(int i) {
// return tests[i - 1];
return tests.get(i - 1);
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
// return sum / tests.length;
return sum / tests.size();
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.size(); i++) {
str += "test " + (i + 1) + ": " + tests.get(i) + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= "
+ 100;
return str;
}
}
return null;
}
public ArrayList<Integer> getTests() {
return tests;
}
public void setTests(ArrayList<Integer> tests) {
this.tests = tests;
}
}

Categories