• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with deck of cards.  RSS feed

 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this assignment that is killing me. I have been at it for 12 hours and am at a dead end.
We are learning enums and my assignment is to replace the named constants in Card.java with enums. Here is my code so far.







and this is the errors I get,

----jGRASP exec: javac -g DisplayDeck.java
DisplayDeck.java:41: error: cannot find symbol
      for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                          ^
  symbol:   variable DIAMONDS
  location: class Card
DisplayDeck.java:41: error: cannot find symbol
      for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                                                 ^
  symbol:   variable SPADES
  location: class Card
DisplayDeck.java:44: error: cannot find symbol
         for (int rank = Card.ACE; rank <= Card.KING; rank++)
                             ^
  symbol:   variable ACE
  location: class Card
DisplayDeck.java:44: error: cannot find symbol
         for (int rank = Card.ACE; rank <= Card.KING; rank++)
                                               ^
  symbol:   variable KING
  location: class Card
Deck.java:47: error: cannot find symbol
      for (String suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                             ^
  symbol:   variable DIAMONDS
  location: class Card
Deck.java:47: error: cannot find symbol
      for (String suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                                                    ^
  symbol:   variable SPADES
  location: class Card
Deck.java:47: error: bad operand type String for unary operator '++'
      for (String suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                                                                 ^
Deck.java:50: error: cannot find symbol
         for (String rank = Card.ACE; rank <= Card.KING; rank++)
                                ^
  symbol:   variable ACE
  location: class Card
Deck.java:50: error: cannot find symbol
         for (String rank = Card.ACE; rank <= Card.KING; rank++)
                                                  ^
  symbol:   variable KING
  location: class Card
Deck.java:50: error: bad operand type String for unary operator '++'
         for (String rank = Card.ACE; rank <= Card.KING; rank++)
                                                             ^
Deck.java:53: error: bad operand types for binary operator '-'
            cards[suit-1][rank-1] = new Card(rank, suit);
                      ^
  first type:  String
  second type: int
Deck.java:53: error: bad operand types for binary operator '-'
            cards[suit-1][rank-1] = new Card(rank, suit);
                              ^
  first type:  String
  second type: int
Deck.java:53: error: incompatible types: String cannot be converted to int
            cards[suit-1][rank-1] = new Card(rank, suit);
                                             ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
13 errors

----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.


Any help would be much appreciated. Thank you in advance for your efforts.
Chad
 
Mark Spencers
Ranch Hand
Posts: 51
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use enums Suit and Rank instead of

Note that you can create additional methods in enum. In Rank enum create method isValidRank and in Suit put isValdSuit. Also add toString method to both enums.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, read what it says about enumerated types in the Java™ Tutorials and the Java® Language Specification (=JLS). That is one of the few parts of the JLS which beginners can understand.

Why have you got static methods? Except for the main method, I have a rule of thumb:
If you haven't got a good explanation for the keyword static, it is a mistake.
As MS has already hinted, it is non‑object‑oriented programming to do that when you can override the toString method instead.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use the == operator to compare reference types; it might appear to work at present because you are using String literals, but it can be relied upon to give undesired results some time or other.
The lowest cards are called deuce and trey; since Ace is the highest card, it shou‍ld be declared last.

MS: why would you need methods to check the validity? Please explain more.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Don't use the == operator to compare reference types; it might appear to work at present because you are using String literals, but it can be relied upon to give undesired results some time or other.
The lowest cards are called deuce and trey; since Ace is the highest card, it shou‍ld be declared last. That is how the base code is written and my professor will fail me on this assignment if I stray too much.

MS: why would you need methods to check the validity? Please explain more.
I didn't write the base code. My professor sent it to the class to modify. Not sure why he is doing anything honestly.
 
Dave Tolls
Ranch Hand
Posts: 2835
30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For those basic errors, those enum values are not part of Card, they are part of Card.Suit and Card.Rank respectively.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think my brain is fried. over 12 hours of homework might be too much.

Here is what I got.

 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dave Tolls wrote:For those basic errors, those enum values are not part of Card, they are part of Card.Suit and Card.Rank respectively.


I'm sorry, i'm not catching what your saying. Could you please give me a little more help?
Thank you
 
Dave Tolls
Ranch Hand
Posts: 2835
30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your original code had multiple errors like this:
DisplayDeck.java:41: error: cannot find symbol
      for (int suit = Card.DIAMONDS; suit <= Card.SPADES; suit++)
                          ^
  symbol:   variable DIAMONDS
  location: class Card

That's telling you that the Card class has no DIAMONDS value...and it doesn't.
The DIAMONDS value is in the Suit class.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:I didn't write the base code. My professor sent it to the class to modify. Not sure why he is doing anything honestly.

What was the base code you were given? We will save a lot of time if you show us that code so we have a better idea of where you are supposed to start and where you need to go from there.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:. . . . My professor sent it to the class to modify. Not sure why he is doing anything honestly.
I presume that was as an example of code needing lots of modification to make it work.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is the base code. It is just a little oracle program for training.







and here is the assignment;

Modify Card.java to use enums for suit and rank instead of named integer constants.
Specification

    Download CardDeck.zipView in a new window (contains Card.java, Deck.java and DisplayDeck.java).
    Create enums to replace the named constants for rank and suit in Card.java.
    Make the changes necessary in Deck.java and DisplayDeck.java so they will work with the new Card.java.

NOTE: There is no grace period for this assignment. No late work will be accepted.
Admin

    Grading
        0 points if your program does not compile.
        +5 for comments, indentation and placement of {} per Style GuideView in a new window.
        +5 for each specification met.
    Submission: Attach an executable JAR file that also contains your .java source code files.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That base code is not object-oriented code and it will take much more beyond just converting those constants to enums to make it better. Are you a beginner Java programmer or are you actually up-and-up on the concepts of object-oriented programming?  Have a look at this example that I posted a week ago: https://coderanch.com/t/678724/java/Merge-Halves-Sorted-Array#3182773 and see if you can follow what is being done with the enums. See if you can understand how that code is more object-oriented than the code you've been given, which isn't OO at all.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:That base code is not object-oriented code and it will take much more beyond just converting those constants to enums to make it better. Are you a beginner Java programmer or are you actually up-and-up on the concepts of object-oriented programming?  Have a look at this example that I posted a week ago: https://coderanch.com/t/678724/java/Merge-Halves-Sorted-Array#3182773 and see if you can follow what is being done with the enums. See if you can understand how that code is more object-oriented than the code you've been given, which isn't OO at all.


I am a beginner, I understand the concept of objects however I really don't know how to effective implement them. I am too green for that. The course I took doesn't help any. I would have understood it better if I had explored it on my own. They didn't even explain what a method was or how it functions until 3/4 of the way through the course. And we weren't told what it was beyond "this is a method" but not what it does or how it does it. I never developed good coding skills because I didn't understand how everything interacts. This course has been so frustrating which sucks because when I first started out, I was enjoying simple coding and now I hate it because I am so lost. Probably one of those courses to weed out people that aren't really committed to computers.

Sorry to vent, but yes, I consider myself a beginner.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:Sorry to vent, but yes, I consider myself a beginner.

No problem. We see students in this kind of situation more often than we'd really like. Know that we sympathize with you.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am less worried about the assignment than you are, Junilu. It is code given for corrections. It might have been easier to write a Card enum from scratch, but this is what has been given.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be fine if the student had enough context to actually be able to understand what to do and how to do it properly. It's more problematic when the student is in way over his/her head. The latter seems to be the situation with OP.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:It would be fine if the student had enough context to actually be able to understand what to do and how to do it properly. It's more problematic when the student is in way over his/her head. The latter seems to be the situation with OP.


Unfortunately, you're right. I wish I would have gotten a more thorough explanation of concepts in this course. But it is the end of the course now and I need to see it through to the bloody end. I will post some questions that I have and maybe that will help me understand.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


[Moderator edit: fixed code tags, removed coloring; that doesn't work with code tags]
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't use color tags -- just put inline comments in the code that you post.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Please don't use color tags -- just put inline comments in the code that you post.

Ok, sorry, I just wanted to highlight what I think I know so it is easier for you to pick out.
What am I wrong on or what am I missing?
The class concentrated more on the specifics than interactions. I am weak in how everything interacts.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chad, this is what I was saying about you not having a good context. Context is what gives you the big picture view and understanding of things.  Based on the comments you added, you seem to have a pretty good understanding of the nuts and bolts of the program. I think a good analogy would be that you were sitting down somewhere and saying "This is a chair, this is a window, this is a radio, this is a belt, this is a door, these are the hinges that keep the door in place, this is so I can lock the door, this is so I can open the window, this is so I can control the radio volume, ... " but you never realize nor recognize that you're sitting in a car.

I think the most astute comment you have there is "That is main method code. not sure why they would have it in a class."

Here's the answer: It doesn't have to be in the Card class; main() just has to be in some class, and since Card is the central concept to this program, whoever wrote that example code chose it to hold the main() method. It very well could have been in a different class, like a CardGame or CardDemo or CardExample class. If that were the case, you would run the program by doing one of the following:
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Chad, this is what I was saying about you not having a good context. Context is what gives you the big picture view and understanding of things.  Based on the comments you added, you seem to have a pretty good understanding of the nuts and bolts of the program. I think a good analogy would be that you were sitting down somewhere and saying "This is a chair, this is a window, this is a radio, this is a belt, this is a door, these are the hinges that keep the door in place, this is so I can lock the door, this is so I can open the window, this is so I can control the radio volume, ... " but you never realize nor recognize that you're sitting in a car.


I think the most astute comment you have there is "That is main method code. not sure why they would have it in a class."

Here's the answer: It doesn't have to be in the Card class; main() just has to be in some class, and since Card is the central concept to this program, whoever wrote that example code chose it to hold the main() method. It very well could have been in a different class, like a CardGame or CardDemo or CardExample class. If that were the case, you would run the program by doing one of the following:


you are exactly right. unfortunately the program approached it from a nuts and bolts method and not a well rounded method of the nuts and bolts and they came together. At first when we were doing simple code I was doing great because I could follow the logic. now not so much.
Pracitce makes perfect I know but that will have to come with time. Unfortunately I don't have "that" much time before my assignment is due.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, here are a few things I can give you to maybe help you get this homework done:

1. An enum defines a set of values that are their own type, the enum type.  That is, if you define an enum named Suit, each value will be of type Suit.


There is no need to validate a Suit enum value. Unlike constants/variables of type int, you don't have to check enum values because it is impossible to assign them values other than those that have been defined in enum. The int variables, however, are still ints and can have the full range of values that int defines, even though logically, you would only have values from 0 to 3 or 1 to 4, depending on how you want to assign meanings to those values.  With an int, you have to translate 1 = SPADES, 2 = HEARTS, etc.  With an enum, SPADES is the value. There is no translation.

2. You can iterate over an enum like so:

The order in which suit will take values is the order in which the values are declared in the enum type definition.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, since an enum value is an object, it has certain methods. You can see what methods an enum value has here: https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html

As with all objects, an enum value has a toString() method. By default, an enum's toString() method will return its name, i.e., the name given to it exactly as it is written in the source code.

For example, if you do this:

The output would be:

CLUBS
SPADES
HEARTS
CLUBS
DIAMONDS
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Also, read what it says about enumerated types in the Java™ Tutorials and the Java® Language Specification (=JLS). That is one of the few parts of the JLS which beginners can understand.

Why have you got static methods? Except for the main method, I have a rule of thumb:
If you haven't got a good explanation for the keyword static, it is a mistake.
As MS has already hinted, it is non‑object‑oriented programming to do that when you can override the toString method instead.


This is a quote directly from my book. 

Class Scope
Static variables have class scope—they can be used in all of the class’s methods. We can ac-
cess a class’s public static members through a reference to any object of the class, or by
qualifying the member name with the class name and a dot ( . ), as in Math.random() . A
class’s private static class members can be accessed by client code only through methods
of the class. Actually, static class members exist even when no objects of the class exist—
they’re available as soon as the class is loaded into memory at execution time. To access a
public static member when no objects of the class exist (and even when they do), prefix
the class name and a dot ( . ) to the static member, as in Math.PI . To access a private
static member when no objects of the class exist, provide a public static method and
call it by qualifying its name with the class name and a dot.


That is why I have static methods. When I try to use certain variables I get the "non-static method cannot be referenced from a static context" message. I know if I create an object out of the variable I am calling I won't need a static method but I am trying to figure out how to do that.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Junilu Lacar wrote:Please don't use color tags -- just put inline comments in the code that you post.
I have corrected that. I think many of those comments shou‍ld be deleted, however. There are some comments which are uselessThat sort of thing is simply a waste of space because it doesn's tell you anything that isn't blatantly obvious to any passers‑by. What follows is even worse, because it doesn't tell you the one thing you actually want to know, viz why on Earth you are starting at 3:-
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:
Campbell Ritchie wrote:Also, read what it says about enumerated types in the Java™ Tutorials and the Java® Language Specification (=JLS). That is one of the few parts of the JLS which beginners can understand.
I didn't give you those hints for nothing. Have you read those links?
. . . This is a quote directly from my book.   . . . We can access a class’s public static members through a reference to any object of the class, or by
qualifying the member name with the class name and a dot ( . ), as in Math.random() . . . .
That fulfils the letter of the law, but not the spirit. Yes, you can gain access to static members of a class via objectName.memberName(), but it shou‍ld also say that is bad style. It shou‍ld have told you that the recommended form is always ClassName.memberName() because static members belong to the class rather than to a particular object.

Always quote the source, in this case name of book, author and if possible page number.
. . . When I try to use certain variables I get the "non-static method cannot be referenced from a static context" message. I know if I create an object out of the variable I am calling I won't need a static method but I am trying to figure out how to do that.
If only Oracle would change the wording of that dreadful error message, which confuses beginners by the million. If only they would stop saying non‑static and write instance instead, which is the correct term.
If you use an enum, which I thought you had been told to (you will get dreadful marks if you shou&wj;ld use an enum and you use numbers ‍), you may not need to create instances. I don't know how many instances of what you need, because I haven't been through the code carefully enough. Sorry. The elements in an enum already are full‑blown objects. We have an FAQ about the main method, which shou‍ld show you how to create instances. I am very surprised you haven't been taught how to create instances. As long as you weren't asleep during that lecture
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:I think many of those comments shou‍ld be deleted, however. There are some comments which are useless

I think the point of OP putting those comments was not as documentation of the code but as an explanation to himself/others of what HIS understanding of the code was. The comments were put there to aid discussion of his understanding or lack thereof about what the program was doing.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:This is a quote directly from my book. 

Class Scope
... To access a private static member when no objects of the class exist, provide a public static method and call it by qualifying its name with the class name and a dot.

That is why I have static methods. When I try to use certain variables I get the "non-static method cannot be referenced from a static context" message. I know if I create an object out of the variable I am calling I won't need a static method but I am trying to figure out how to do that.

What you're doing is what's called a "workaround." You're trying to work around a problem instead of addressing the root cause. With a workaround, you may be able to deal with a problem and continue but you don't really eliminate the problem; it's still there, just waiting to rear its ugly head again when you've gotten yourself deeper into its trap. In this case, the problem you're going to get trapped in is that you're not properly organizing your program elements and separating what should belong to instances and what should belong to the class, what should be treated with objects in mind and what can be treated without objects in mind.

Around here, MainIsAPain (←click that, it's a link). We encourage folks to make their main methods as small as possible and get right down to dealing with objects instead. This way, you minimize the confusion and the likelihood of getting caught in the static trap when you try to work around the problem that causes the "non-static method cannot be referenced from a static context" message.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's make a little analogy here so you can understand the purpose of the main() method. Think of your program as a car engine.  Now, think of your main() method as your car's starter. If you're not familiar with cars and how they work, here's a little primer:

In a car, the starter is a motor that is attached to the car's main engine. Under normal operating conditions, an engine keeps itself running. As long as there's fuel being fed to the engine and a way to ignite that fuel, the engine will basically keep itself running through what's called the "combustion cycle." When the engine is off, it needs a little help to start the combustion cycle. That's where the starter comes in. The starter cranks the engine and provides the initial energy needed to get the pistons and crankshaft moving. Once the pistons and crankshaft starts moving and a few initial explosions inside the cylinders happen, the self-perpetuating combustion cycle gets started. Once that happens, the starter can disengage and at that point, it becomes extra baggage. In simpler terms, the starter on an engine is simply used to bootstrap the combustion cycle and get the engine running on its own.

The main() method of a Java program is equivalent to the starter of a car engine. That's why it should be small, just as a starter is a relatively small component of the engine. Once your program has started, the main() method really shouldn't come into play much in the operation of the program. This is why we recommend a main() method that looks something like this:

That's it! All the logic for playing the card game should be in a CardGame object's (an instance of the CardGame class) play() method. This main() method can go in a class called CardGameStarter, for example:

To run this program, you'd type java CardGameStarter on the command line. This is like you turning the ignition to start your CardGame class. In most cases, this is the only static method you'll need in your program. The rest of your program can be written with proper objects and instance methods/variables in mind. This is how you avoid getting into that static vs. non-static workaround trap.

Does that make sense so far?
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now let's look at your attempt to define a Suit enum.

To me, this code displays a lack of basic understanding of what an enum is for. Why are you attaching a number to the value of each enum? Of what significance is the number 1 to the idea of "DIAMONDS" as a suit? When you look at a regular deck of cards and you see the Ace of Diamonds, do you think, "Ah, yes, Diamonds is 1. Yup, and Spades is 4." You don't ever do that, right? So why would you want to do that in your program?

Here's the context you're missing: Before it was possible to define enumerated types in Java, you had to resort to other ways to represent these kind of abstract ideas in your program. There is no native type in Java to represent an idea like a card suit. You could use full-blown class but that seemed like overkill and it made dealing with values overly complicated. A suit only has four distinct values: SPADES, HEARTS, CLUBS, and DIAMONDS. Defining a class to represent SUIT seems like a bit too much trouble just to represent four distinct and unique objects of the same class.

So, most programmers resorted to just mapping the idea a "suit" to a limited set of numbers. In the case of a Suit, the numbers were usually 0 for SPADES, 1 for HEARTS, 2 for CLUBS, and 3 for DIAMONDS. The numbers usually started from 0 because you could use these values as indices to an array of Suit values, which was pretty convenient. To make it clear that these int values had special meanings, they were usually assigned symbolic names and made static final because once assigned, they didn't change. In other words, you defined symbolic names for the different int values that represented the idea of a card's suit.

This is why you have that initial definition of Suit values as constants:


This scheme is fine if you stay within the limits of values that you've defined for Suit. However, since SPADES, HEARTS, etc. are only names you've assigned to specific int values, there's no guarantee that somebody (maybe even you, the programmer) might try to use an "illegal" value like 5, which isn't mapped to any idea of a Suit, to represent a suit. What do you do then?

Well, you can see in your original program the things you have to resort to.  In the suitToString() method, for example, you have to do a range check of the int value that gets passed in. If the value passed in is mapped to a proper Suit, then the conversion can be done. Otherwise, you have to reject the int value because while it's a valid int value, it's not an int that represents a valid Suit. In other words, you, the programmer, have to make sure that the semantics of Suit as an integer are strictly adhered to. You have to enforce the value checks. Without these checks, your program would have all sorts of problems with ints that didn't map to a proper suit.

The same thing goes with the Rank values that you mapped to int values.

With the introduction of enum, the problem of checking the values fell from the shoulders of the programmer to the JVM, where it should be. Now when you define an enum, Java sees these as literal values and treats them like any other literal value. Each enum value is also an object, so it has an identity and some behavior that you can invoke via its methods. Enum values are special kind of objects but not that special. An enum value is only ever equals() to itself. In fact, because an enum value is unique, you don't even have to use equals() to compare it with another value of the same enum type.

The condition in the if statement uses the == operator instead of equals(). Normally, when comparing objects for equality, you are told to avoid using == and use equals() instead. However, since an enum is itself its own value and there is ever only one of each value in the JVM on any given run, the reference equality operator == gives you the same results as the equals() method, so when it comes to enum values at least, using == is fine and actually preferred.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
chad jensen wrote:
Campbell Ritchie wrote:Also, read what it says about enumerated types in the Java™ Tutorials and the Java® Language Specification (=JLS). That is one of the few parts of the JLS which beginners can understand.
I didn't give you those hints for nothing. Have you read those links?
. . . This is a quote directly from my book.   . . . We can access a class’s public static members through a reference to any object of the class, or by
qualifying the member name with the class name and a dot ( . ), as in Math.random() . . . .
That fulfils the letter of the law, but not the spirit. Yes, you can gain access to static members of a class via objectName.memberName(), but it shou‍ld also say that is bad style. It shou‍ld have told you that the recommended form is always ClassName.memberName() because static members belong to the class rather than to a particular object.

Always quote the source, in this case name of book, author and if possible page number.
. . . When I try to use certain variables I get the "non-static method cannot be referenced from a static context" message. I know if I create an object out of the variable I am calling I won't need a static method but I am trying to figure out how to do that.
If only Oracle would change the wording of that dreadful error message, which confuses beginners by the million. If only they would stop saying non‑static and write instance instead, which is the correct term.
If you use an enum, which I thought you had been told to (you will get dreadful marks if you shou&wj;ld use an enum and you use numbers ‍), you may not need to create instances. I don't know how many instances of what you need, because I haven't been through the code carefully enough. Sorry. The elements in an enum already are full‑blown objects. We have an FAQ about the main method, which shou‍ld show you how to create instances. I am very surprised you haven't been taught how to create instances. As long as you weren't asleep during that lecture


Thank you guys for your help so far. I do understand that instance variables are just variables that are used to create an object then they are thrown away. Therefore if you try to call an instance variable, it will give you an error because the instance variable changes with every new object created. I just am trying to figure out how to call that instance variable for each objects creation.
 
Campbell Ritchie
Sheriff
Posts: 55351
157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
chad jensen wrote:. . . I do understand that instance variables are just variables that are used to create an object then they are thrown away. . . .
No, that is mistaken. They are recorded in the object, or until their values are changed until the object is no longer required. You might be thinking of constructor arguments there.
 
chad jensen
Greenhorn
Posts: 29
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
chad jensen wrote:. . . I do understand that instance variables are just variables that are used to create an object then they are thrown away. . . .
No, that is mistaken. They are recorded in the object, or until their values are changed until the object is no longer required. You might be thinking of constructor arguments there.


Sorry I misspoke, yes they are stored in the object, but they aren't stored in the class. The are only present in the class until the object is created, at which point they are no longer stored in the class, they are stored in the object of that class, the "instance" of the class. To call a value attached to an object of a class, you can't call the class as the instance variable value always changes, you have to access the value from the object. or that's how I understand it. Is that correct?
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance variables are NEVER stored in a class.  Don't think of these things like that. You'll only mislead yourself. Think of an instance variable as something that is inherent to an object, just as you have two eyes, a nose, etc.  We say "All people have a nose" (ignore the fact that some people may be born with congenital defects) -- That means that when a Person is born(instantiated), he/she is expected to have a nose. The class Person defines this attribute. It doesn't mean that there's like a giant bin of noses somewhere in heaven where the blueprint for a Person is defined, then when a child is born, one nose is taken out of that bin and given to the child. No, it doesn't work that way.

Be careful how you phrase things because we will take it very literally. If you say the class stores something, we will interpret that as you saying that the class has a static field that stores some value.
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think of the class as a blueprint of an object. Objects are the real things. Classes are just definitions of what an object would look like. Think of class static members as little attachments to the blueprint. Like a calculator attached to the blueprint of a floor plan, so that someone looking at the blueprint can verify the area calculations on that blueprint.  Or a sticky note on a blueprint to remind the foreman what the cell# of the architect is.  When you create the actual floor or building, you won't see a calculator embedded in it, right? You wouldn't see the cell# of the architect etched into the floor, right? The calculator and the sticky note were attached to blueprint for convenience but they aren't part of the real thing that you create. Static methods and variables are kind of just convenience things, too, that are attached to class (the blueprint), not the object (the real thing).
 
Junilu Lacar
Sheriff
Posts: 10949
158
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let me try to stick with this blueprint metaphor.

So, let's say the blueprint for a house specifies that a standard window must be 50 inches tall. In code, that specification might look something like this:

The constant STANDARD_HEIGHT is a static member. It is attached to the Window class and it defines a standard height for windows. The no-argument constructor uses that value to create windows that have that standard height. On the other hand, there is another constructor that you can use to create windows with a custom height, possibly different from the STANDARD_HEIGHT.

So, out on the job site, the homeowner looking at an actual window may not know whether or not it is a standard-height window. So, he asks the foreman, "Is this a standard-height window?"  Let's say the foreman doesn't like to memorize a lot of things so he says (looking at the blueprint), "Let's see... it says here that a standard-height window is 50 inches in height... let me measure this really quick... yup, it's 50 inches, so it's a standard-height window." So the actual window (the instance) has a height that is equal to the STANDARD_HEIGHT value.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!