• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Switch Case and enum

 
Ranch Hand
Posts: 1402
3
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi @ll,

I have in the same class the next code:



and in a method compares, this one:




My question is if how to instead of use the literal ROCK, could I get it form the enum. At the moment I get the next error:



I tried this conversion:



and I got this message:




Any idea, please?

Regards, Isaac
 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since Java5 it has been possible to use enum constants directly after case.
case PossibleChoices.ROCK:

Don't use underscores in class names.
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why aren't you using the enum values themselves? Even if you have the value as a String, you can covert it with: Posible_Choices c = Posible_Choices.valueOf(s);


 
Angus Ferguson
Ranch Hand
Posts: 1402
3
Netbeans IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I dont use it via parameter because I am callin that function from a place without access to that enum.

This is my whole class:



The error is still like this:


Any idea, please?
----
 
Jeanne Boyarsky
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Isaac Durá wrote:Any idea, please?


As I wrote in my post, convert your String to the enum type before the switch statement



Also, consider refactoring your code to not use a String value for it in the first place. You are losing some of the benefit of an enum.
 
Angus Ferguson
Ranch Hand
Posts: 1402
3
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have refactor the code, creating a class only for the enum



And then :

 
Jeanne Boyarsky
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is o2.ask_Element()?
 
Saloon Keeper
Posts: 15484
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Finally, I believe that enum constants in switch statement cases must be referred to by their unqualified name:
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Isaac Durá wrote:I have refactor the code, creating a class only for the enum . . .

I trust that means you only have one class with ROCK PAPER and SCISSORS in.
I cannot understand why they were not accessible if you had a public class before . . . unless you mistakenly made that class a nested class by mistake. That sort of mistake is very easily made; all you have to do is put a { or a } in the wrong place.
 
Angus Ferguson
Ranch Hand
Posts: 1402
3
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What I would need is convert this:



into a String, not the contrary.

Any idea, please?
 
Angus Ferguson
Ranch Hand
Posts: 1402
3
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What is o2.ask_Element()?

It is a bad name I put for test...

When I put:



outside the brackets of the main class, but Netbeans ask me for change the name of the file.

 
Rancher
Posts: 5008
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

An enum can have a method that returns a String.  See the example at the end of the tutorial: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
 
Stephan van Hulst
Saloon Keeper
Posts: 15484
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Isaac Durá wrote:What I would need is convert this [...] into a String, not the contrary.


Why? In this scenario strings are only useful for printing. Don't use strings.

It is a bad name I put for test...


Jeanne meant, what is the return value of that method call, an enum or a String?

When I put [...] outside the brackets of the main class, but Netbeans ask me for change the name of the file.


Put the enum in a separate file.
 
Stephan van Hulst
Saloon Keeper
Posts: 15484
363
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A few notes on naming your enum:

  • Possible is spelt with two s'es.
  • The part 'Possible' is redundant. The values are possible by virtue of their existence.
  • Enum names should be singular: Choice instead of Choices.
  •  
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Here's my take on what's happening here.

    Isaac, you have been given a lot of advice and these are, in and of themselves, all good and valid. However, all these are "in the small." That is, most of it focuses on details that are just small symptoms of a larger problem. And while it's fine to treat the symptoms, I'm afraid that addressing each symptom in isolation without connecting them to the larger problem will not do you much good.

    The larger problem that's creating confusion for you is that you are having difficulty grasping the idea behind object-orientation. In order to use enums properly and effectively, you need to understand how object-orientation plays into their design and usage with the rest of your program.

    These are some parts of your code that give off a very strong smell, that is, it gives me a sense of something very wrong with your design thinking:

    1.  Class names should be nouns or noun phrases. Classes should be thought of entities or things that have behaviors.  The name CompareChoices does not carry this idea of "thing" or "entity". Rather, it carries the idea of an "action" or a verb.  This is a conflict in abstractions and it confuses your brain.  It's like calling your hand a writeNote or your foot a wearShoes or your eye a seeColor.

    2. You are creating inappropriate specializations with PlayerA and PlayerB classes.  What's the difference between a PlayerA object and a PlayerB object in the context of a Rock-Paper-Scissors game?  There is none. Both players have the same general behavior.  What's more, in the RPS game, there's actually no need for a Player object. I suppose you could find a way to introduce a Player concept but, IMO, doing so is fraught with peril if you don't have a good grasp of OO. Just figuring out how to make the RPS enum properly object-oriented is challenging enough without adding a Player concept.

    3. I can't even imagine what a Ties object is all about. (Edit: well, Ok, I can imagine what it's about but it's an idea that I think is not naturally represented as an object. Rather, it's actually a condition that some object should be able to recognize as existing or not. That is, you should be able to ask whether ROCK vs ROCK or ROCK vs PAPER is a tie or not, according to the rules of RPS)

    (continued)
     
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    As simple as it may seem, I actually consider implementing the RPS game as an object-oriented design in Java an intermediate to advanced challenge. However, here are some things you may want to consider if you want to continue with this exercise and do it in a proper OO manner. (On the other hand, there's no better teacher than experience and one of the best ways to learn is by making mistakes)

    1. Object-orientation is mostly about assigning responsibilities to the proper entity abstraction (objects).  

    2. Software classes do not necessarily represent real-world, physical objects. Many classes are simply abstractions that help us think about actions performed on data as though some animate and cognitive "thing" is performing them. Take for example an Iterator. Show me a live Iterator in the real-world. You can't because it's just an abstract idea. Yet in software, you can "ask/tell" an iterator to give you the next() element in its underlying collection. You can ask the iterator if it has another element via the hasNext() method.

    3. In OO, methods can be thought of as ways to exercise the "capabilities" of the object to which they belong. Going back to the Iterator example, it has the capability of "knowing" if there are more elements in the underlying collection. It can tell you what that next element is as well.  By calling the hasNext() and next() methods, respectively, you can exercise these capabilities of an Iterator.

    In the case of the RPS game, the main entity is a mostly abstract concept. You have already identified it: the enum that defines ROCK, PAPER, SCISSORS.  I say "mostly abstract" because while you can think of them as "things", it's not natural to attach behaviors or capabilities to them.  However, if you were to design it as a Java enum, it turns out that it makes sense to give the enum certain capabilities.  By doing so, you move the responsibility of performing calculations and actions closer to the data. This results in better encapsulation and abstraction.  Training your brain to think this way is not easy though and you usually have to run through the design process a few times to get a good "feel" for thinking in terms of entity/abstraction + capabilities/responsibilities + knowledge = objects + methods + fields/data.
     
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    To give you a concrete way to relate to the above, here's what a "conversation" in an object-oriented implementation of RPS might look like:

    Can you identify the abstraction/entity and its capabilities in the above code?  When you read the code, doesn't it tell a pretty good story about how a game of Rock-Paper-Scissors is scored? In this high-level code, do you see detailed calculations or are those calculations (knowledge+capabilities) hidden somewhere in one or more of those method calls? Do you see how the "responsibility/capability" has been assigned to the abstraction/entity?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15484
    363
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Besides the excellent points that Junilu made, Isaac, you have the bad habit of not following up on your questions with your final result. That gives us no way to comment on your result and identify areas that can still be improved.
     
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    If you're wondering why I use the term "conversation" to describe what's happening in the code, here's how I think of the code when I read it:

    During the design process, these are the kinds of questions I ask:
    1. Who should be responsible for determining a tie between two moves?
    2. Who should be responsible for determining a win?
    3. Who should ask for a player's move?
    4. Who should convert the console input into a Move object?
    5. Who should ...
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

     you have the bad habit of not following up on your questions with your final result. That gives us no way to comment on your result and identify areas that can still be improved.



    I hadnt seen the post, till now. I always try to put the final solutions, even when I solve it myself.

    Ok I am improving the code in base to the suggestions and I will place it here.
     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Isaac Durá wrote:. . . I hadnt seen the post, till now. . . .

    You shou‍ld develop the good habit of making sure to read all replies. Creating many threads makes it harder for you to keep track of replies, which is another reason why we discourage multiple threads.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Yes open specific topics inside the same general one....I need to keep it wider...
     
    Bartender
    Posts: 10780
    71
    Hibernate Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Junilu Lacar wrote:If you're wondering why I use the term "conversation" to describe what's happening in the code, here's how I think of the code...


    I hate to say, but 'ties()' seems redundant to me. All you need is:
    @Isaac: And furthermore, the place to define this method is in the enum - it's one of the things that makes them so powerful in Java. Eg:And voilà, the entire "guts" of the game in a single enum.

    HIH

    Winston
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    That logic with the enum is very good.

    My requirement are (I know they are 2 players in the real game), but in this case player A always should choose Paper and the other player is the machine itself, it is the same for now, if it is a non sense, but this are my requirements.

    I would like to improve this enum, mainly eliminate the return null, respecting the current design of the program.


    Any idea for eliminate the return null, please?
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    What's the difference between a PlayerA object and a PlayerB object in the context of a Rock-Paper-Scissors game?



    Player in base of my requirement is the only active player. I know it is a non-sense, but at the moment PlayerA only chooses Paper.
     
    Junilu Lacar
    Sheriff
    Posts: 17644
    300
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Winston Gutkowski wrote:
    I hate to say, but 'ties()' seems redundant to me. All you need is:[code]...
    if (player.beats(computer)) {
      // whatever
    } else if (computer.beats(player)) {
      // whatever
    } else {  // the result must be ...


    Not sure why you'd hate to say that, it's a perfectly reasonable and logical argument.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Ok I have refactored it a little bit. Ties object is not there anymore. The main reason why I create 3 objects, one for playerA, playerB, tie is because unfortunatelly I am still using their getter and setters for set their counters...

    I know I should "tell" instead of "say".


    Test it by all means, but you won't find what it wrong with it. You sh‍ould have a method which adds points to the current score. Much more useful than a set method. It also means you can, as Winston Gutkowski often says, “tell, don't ask.”




    The internals of for my are still setting values in a field of the object, or it is related to an ArrayList?





     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    During the design process, these are the kinds of questions I ask:
    1. Who should be responsible for determining a tie between two moves?
    2. Who should be responsible for determining a win?
    3. Who should ask for a player's move?
    4. Who should convert the console input into a Move object?
    5. Who should ...



    1.) As the playerA always choice Papier, and player B is the computer itself, a tie is considered when randomly the machine choice Paper.
    2.) The combination of choices in the method beats()
    3.) Nobody playerB make 100 choices, playerA always choice Paper.
    4.) There is not consolo input.


    I have improve the code a little bit, having into account that my requirement for this version is that player A always chooses Papier and player B is a random value choosed by the computer.

    The bellow code works, but I would like to improve the design and implementation.








    And the tests I have for it:













    As I said it works, but I would like always respecting the fact that player A always choice Papier and playerB is the computer, improve my desing and my code for this particular case.

    Any idea, please?


     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    And the class Player, which was missing:

     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    My, that looks confused. You still don't seem to have grasped object orientation.
    Why do you have points A and B in the same class? Why two fields? You could have two people playing and set each with different scores for each other.
    Why have you got those setXXX methods rather than win lose or draw/tie methods? Didn't you understand what I said last week about tell, don't ask?
    Why do you have a switch to choose from the options ROCK, PAPER, SCISSORS, when you can simply use the array index?
    Why are you using Strings for equality when you already have enum constants; even the Java® Language Specification says you can use the == operator.
    Why are you using the Enum class? If your enum is called Choice, say Choice.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Didn't you understand what I said last week about tell, don't ask?



    No Ididnt I wrote about it in this post if you want to scroll up a little bit.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Why are you using Strings for equality when you already have enum constants; even the Java® Language Specification says you can use the == operator.



    Where here:


     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Why do you have points A and B in the same class? Why two fields? You could have two people playing and set each with different scores for each other.



    Yes I wrote it for make easier read the code for myself, now it is fixed with only one field.
     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Isaac Durá wrote:. . . Where here:

    No. I meant in line‑91, but the code you quoted in that method is no better. The whole idea of an enumerated type is that you use an enumerated type. You do not try to convert it to Strings or anything like that. You can do everything with the enum constants, including equality and switch‑case.

    When you are playing a game of football, you do not say to the team scoring a goal, “You had three goals before, so now you have four.” You add one to the previous score. You do not want to ask how many points A or B has and then add one to it. You simply add to their points. You do not need to ask for the old score; you simply need to tell the object to add one. That is what you shou‍ld be doing here. Don't ask a player object how many scores it has; simply tell it to add one. That is what I meant about the add method above.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I have refactor lot of things following the advice here given.

    Here I get a compilation error:



    Any idea, please?
     
    Rancher
    Posts: 4801
    50
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    The case needs to be one of the enum values.

    What you have at the moment is the equivalent of:
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    But



    returns an enum value



    I also would like to remove the null return
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15484
    363
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Switch cases need to be compile time constants. The variable choice is not a compile time constant. Typically, with enums, you would use the enum constant names directly as switch cases:

    I'm not convinced you need a switch statement there though. Actually, I'm not even sure what the meaning of a Player.winRound(Player, Player, Player) method is. You should take a step back and look at your design, because it's confusing and it will lead to bad implementation.

    Before you write any code at all, describe in English how a game of Rock, Paper, Scissors is supposed to unfold. From that you can then distill interfaces, and write documentation and tests for them.
     
    Angus Ferguson
    Ranch Hand
    Posts: 1402
    3
    Netbeans IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    This are the requirements:


    So we can start from the beginning...

    Any inicial idea, for the design, please?

    Regards, Isaac
     
    Campbell Ritchie
    Marshal
    Posts: 79151
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Isaac Ferguson wrote:. . . Any inicial idea, for the design, please? . . .

    Apart from what you have already been told for about two weeks on this thread?
     
    reply
      Bookmark Topic Watch Topic
    • New Topic