Win a copy of Terraform in Action this week in the Cloud forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Java Code Revision

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I need to revise my java code for my assignment. My assignment is about matching pennies game. It is played by a computer and a user.

1.Each player has same number of penny. Running the program should first ask the user for the number of starting pennies for each player,for example 5 or any other number. I have done this part.

2.For each round, the two players take turns: user should be able choose “Heads” or “Tails” using a number for each (1or 2) and user should write his/her choice on console(I am having issues for this part) and computer will select his/her choice randomly. If the pennies match (both heads or both tails), then User keeps both pennies, so wins one from Computer (+1 for user, -1 for computer). If the pennies do not match (one heads and one tails) computer keeps both pennies, so receives one from user (-1 for user, +1 for computer)After the user’s choice, computer should be able to choose one of the two options as well(randomly). To make it clear, the human chooses heads or tails, the computer picks randomly.The game loop consists of a player selecting appropriate input (heads or tails) via an Input Dialog, and the computer selects between the two randomly, using e.g. Math.random().I am having issues for this part.

3.When one of the two players runs out of pennies, display who won each round and the final winner (user or computer). I have done this part too.

Could you help me for the missing part? Please see my code at below:

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

I am having issues for this part.


Please explain what problems you are having.
 
Sheriff
Posts: 16719
278
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 each player has the same number of pennies to start with, why are you prompting for both on lines 15-18? Wouldn't it make more sense to prompt for "How many pennies does each player start with?" just the one time?


Also, if the human player has to choose heads or tails, why would you assign a randomly generated choice to coin_human on line 25? Wouldn't you ask the human play to enter that choice instead?

Also, why would you call the method generateTicketNumber()? Do the requirements say anything about ticket number? This looks like you just copied it from a different program that had a very different set of requirements. If you're going to copy something, at least make it make sense in the context of your program that you're copying to.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
And welcome to the Ranch!
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
The convention for variable names in Java is to use lowerCamelCase which starts with a lowercase letter and subsequent words in the name are capitalized. In your case, it would be coinHuman rather than coin_human. Lower snake case, which is what you're using, is the convention used in Python.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
Consider using java.util.Random instead.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
You might want to double check your "Who won?" logic on lines 44 to 49.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
You would make things much easier on yourself if you break out smaller pieces of functionality to separate methods like you have in the curiously-named generateTicketNumber() method. Having everything in main() is a pain.

If you break out each task to a separate method, you could have much cleaner and clearer code in main():

Since each method will solve one piece of the problem, it will be easier for you to keep track of what you've done and what you still have to do. It's also easier to debug programs that are organized in smaller chunks of functionality.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for all your work. I am just new to java and I am not good at writing the codes, that's the reason it looked complicated.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am trying to add your code inside my code but I am having problem with it. Could you please write the complete code?
 
Junilu Lacar
Sheriff
Posts: 16719
278
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

Sarah Semrad wrote:I am trying to add your code inside my code but I am having problem with it. Could you please write the complete code?


Sorry, we don't do that here. We'll give you examples to learn from and follow but we won't do your work for you. If you have any questions about the code examples I gave, I'll be happy to answer them.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All right no problem. thank you anyway
 
Bartender
Posts: 4709
183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since the sum of computerPennies and humanPennies is always twice the startNumber of pennies of each player, you need only one score, and see if it becomes 0 or 2 * startNumber.
 
Marshal
Posts: 8145
572
Mac OS X VI Editor BSD Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sarah Semrad, if you are intended to modify your original post with new details, in this case modified code, please post an updated code instead. And the reason being for that is, so that replies you got already would still make sense given the original post.
Staff note (Liutauras Vilda) :

OP's edits were not approved, so the original post is still intact.

 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sarah Semrad wrote:I need to revise my java code for my assignment. My assignment is about matching pennies game. It is played by a computer and a user.

1.Each player has same number of penny. Running the program should first ask the user for the number of starting pennies for each player,for example 5 or any other number. I have done this part.

2.For each round, the two players take turns: user should be able choose “Heads” or “Tails” using a number for each (1or 2) and user should write his/her choice on console(I am having issues for this part) and computer will select his/her choice randomly. If the pennies match (both heads or both tails), then User keeps both pennies, so wins one from Computer (+1 for user, -1 for computer). If the pennies do not match (one heads and one tails) computer keeps both pennies, so receives one from user (-1 for user, +1 for computer)After the user’s choice, computer should be able to choose one of the two options as well(randomly). To make it clear, the human chooses heads or tails, the computer picks randomly.The game loop consists of a player selecting appropriate input (heads or tails) via an Input Dialog, and the computer selects between the two randomly, using e.g. Math.random().I am having issues for this part.

3.When one of the two players runs out of pennies, display who won each round and the final winner (user or computer). I have done this part too.

Could you help me for the missing part? Please see my code at below:

 
Junilu Lacar
Sheriff
Posts: 16719
278
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
Hi Sarah,

It looks like you've made a bit of progress. Instead of posting a big block of text, can you be more specific about what problem you need help with? That's a lot to read.
 
Norm Radder
Master Rancher
Posts: 4510
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is that the correct code for the problem?  I can't see that the code is related to the problem statement.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
Norm is right, that code solves an entirely different problem. Instead of copying code wholesale, you might want to play around with small pieces and understand what they do. There's no rule that says you have to solve everything all at once. For example, I might start by asking "How do I make random tosses to represent the computer's moves?" and then think, "Well, that's too hard. How about I try something simpler, like just print out 10 heads." Then you can try something like this:

Obviously, that's not what you actually want but it gets you a little closer. Then you can think, how about if I make it alternate between heads and tails? To do that, you only have to change one little thing, like this:

While that's not what we really want, it gets us closer. Now we can say "Ok, so how do I make this random?" Again, since we already have a program that works, we just have to to change it a little bit:

With this small change, we now have 10 random tosses!

Do you see how this works? Try to start with something that works even if it's obviously wrong, then start making small changes to get it closer to what you really want the program to do. If you try to solve everything all at once and write dozens of lines of code, the likelihood that you'll make a mistake in multiple places will be much higher than if you just keep tweaking and adding small increments to code that is already working to some degree.  

A big program that works almost always evolves from a small program that works. Trying to write a big program all at once and expecting it to work hardly ever works out.
 
Marshal
Posts: 74393
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's see if we can create a List<Toss> with a Stream.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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
Another way:

Caveat: I haven't tried this code out, just wrote it off the top of my head.
 
Campbell Ritchie
Marshal
Posts: 74393
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry for producing code you might not have been familiar with; Junilu pointed this out to me.
Look in the Java™ Tutorials and the JLS (=Java® Language Specificafion), where you can learn about enum types (old name=enumerated types). Basically, you have a class called Toss which has two (static) instances called HEADS and TAILS. I know you might say you throw a coin rather than tossing it, but if you write throw and similar you might get compiler problems because you are using a keyword out of context. I once spent over an hour trying to work out that very problem with throw and was mentioned in the lecture the following day. When you have read the two links, you will know you have the option of enahncing that enum with methods, but that is sort of beyond the scope of this thread.
What about Streams? They take a source of information. They run through all the elements from that source, but can remove elements as required. In my case I used a method, which produces a (10‑element) Stream of ints, “randomly” selected to start from 0 and to be less than 2 (i.e. 0/1).
If you have read my two links, you will know an enum has a method called values(), which returns all the possible values as an array. Another visit to the Java™ Tutorials will tell you the strange syntax with -> gets you whichever Toss matches the “random” number. I shall challenge you to suggest an improvement over using the “magic number” 2.
What the method toList() does should be obvious. If you find its documentation, that tells you how it works, and also that it was introduced in Java16. Julilu and I have both shown you another way to create a List. If you have the time to read them, the java.util.stream package summary and the Collectors class may supply you with more information.

I shall let Junilu explain his solution himself; I think both solutions are good and elegant, and they show you that in programming there are often several correct ways to obtain the same result.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you all. Code is alright now.
 
Campbell Ritchie
Marshal
Posts: 74393
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please show us how you improved it.
 
Junilu Lacar
Sheriff
Posts: 16719
278
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

Campbell Ritchie wrote:I shall let Junilu explain his solution himself


The solution I gave applies encapsulation, abstraction, and limiting scope to manage complexity.

As with Campbell's solution, we start off by defining an enum type to represent the discrete HEADS and TAILS values. This eliminates the need to translate an integer to "heads" or "tails". This is a better abstraction than using two integer values to represent heads and tails. Also, we encapsulate the random generator inside the enum type thus keeping its scope as small as possible. We do this to manage and control the extent of its use, making it easier to reason about the program.

The static randomToss() method encapsulates the logic needed to simulate a coin flip that results in either HEADS or TAILS, creating a more meaningful abstraction and separating intent from implementation.

As for getting 10 random tosses, I show another way of doing it by using the general Stream.generate(Supplier<T>) method, passing in a method reference as the supplier argument. We limit the stream to 10 elements and collect them into a List.
 
Norm Radder
Master Rancher
Posts: 4510
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please edit your posts and wrap the code in code tags:  Select the code and press the Code button.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;
public class OddsAndEvens {
   public static void main(String args[]) {
       System.out.println("Let's play a game called \"Odds and Evens\"");
       System.out.print("What's your name? ");
       Scanner console = new Scanner(System.in);
       String name = console.nextLine();
       System.out.println("Hi " + name + ", which do you choose? (O)dds or (E)vens? ");
       String user = console.nextLine();
       boolean even_pick = user.equalsIgnoreCase("E");
       if (user.equalsIgnoreCase("E")) {
           System.out.println(name + " picked evens. The computer will be odds!");
       }

       else if (user.equalsIgnoreCase("O")){
           System.out.println(name + " picked odds. The computer will be evens!");
       }
       System.out.println("-----------------------------------------------");
       System.out.println("How many \"fingers\" do you put out? ");
       int num = console.nextInt();
       Random rand = new Random();
       int computer = rand.nextInt(6);
       System.out.println("The computer plays "+ computer+ " \"fingers\"");
       System.out.println("----------------");
       int sum = num + computer;
       boolean oddOrEven = sum % 2 == 0;
           if ( oddOrEven == true){
           System.out.println(num + " + " + computer+ " = " + sum + " is..... even." );
               if (even_pick == true) {
                   System.out.println("That means "+ name + " wins!");
               }
               else{
                   System.out.println("The computer wins!");
               }

           }
        else{
           System.out.println(num + " + " + computer+ " = " + sum + " is..... odd." );
           }
       System.out.println("------------------------------------------");
   }


}
 
Greenhorn
Posts: 1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Campbell Ritchie
Marshal
Posts: 74393
335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
SS: why have you got so many posts? How do they differ from one another? Do you have a question about any of them?
AG: welcome to the Ranch Do you hve a question? Are you suggesting that as a complete solution? I am afraid I don't like it as a solution. You haven't created any objects to model the game. You are using Strings like HTTHHHHTHTT which are not at all good design. You repeatedly wrote while (true) ..., which I don't like. You have methods far too long, particularly main(), whose ideal length is one statement (link). You have got all your method static, which suggests you aren's writing object‑oriented code.

As Norm said, please always use the code button; I have added code tags to your code and doesn't it look better now.
 
Sarah Semrad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Aimee, it is very valuable code. My problem statement is abit different in a game of matching coins with two players, supposed wins one unit of value when there are two heads, wins
nothing when thereare two tails, and loses (1 / 2) unit of
value when there are one head and one tail. Determine the
payoff matrix, the best strategies for each player, and the
value of the game to A.
 
Saloon Keeper
Posts: 1672
61
Eclipse IDE Postgres Database C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:SS: why have you got so many posts? How do they differ from one another? Do you have a question about any of them?
AG: welcome to the Ranch Do you hve a question? Are you suggesting that as a complete solution? I am afraid I don't like it as a solution. You haven't created any objects to model the game. You are using Strings like HTTHHHHTHTT which are not at all good design. You repeatedly wrote while (true) ..., which I don't like. You have methods far too long, particularly main(), whose ideal length is one statement (link). You have got all your method static, which suggests you aren's writing object‑oriented code.

As Norm said, please always use the code button; I have added code tags to your code and doesn't it look better now.



As of this moment, I think I see a stuttering repeat of 5 or 6 instances of her top-level class in the output, not sure how that happened.

I was going to note that Pennies is the only accepted plural of penny, the unit of currency, but the plural of the PenneysGame class itself is more problematic than its name.
 
reply
    Bookmark Topic Watch Topic
  • New Topic