Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Help with first Java program?

Options
  • 23-03-2013 10:48pm
    #1
    Closed Accounts Posts: 7,872 ✭✭✭


    Hey, I've decided to try and learn Java. I have no coding experience at all, it's my first week looking at any programming type stuff, so am a complete noob in relation to anything like this, so be gentle :pac:. I've got myself a Java for beginners book and am working through it.

    So I've tried to make my first little Java program from scratch. It's in effect a Blackjack/21 style game, but simpler. I've tore it down and rebuilt it about a dozen times and I finally have something that, almost, works. There's just a couple of little problems left now that I just can't seem to figure it out. So I was wondering if anyone could give me some pointers?

    Here's the code I have:

    Basically how I want it to work is:
    1.When you start the program it displays "Card" and "Total" then deals a card. "Total" is the "card" number plus the previous card number (if there was one).
    2. Then it asks you if you want to "hit or stick". (If you want another card or not)
    3. If you type "hit" it gives you another card, displays the number of that and then adds the previous card number to this number and adds it to the total and displays that.
    4. If total is > 21 at any point it displays a message telling you you have "gone bust" and the game ends.
    5. If after being dealt a card and it asks if you want to "hit or stick" and you type "stick", it displays a message depending on the current value of "total". Total <= 17 displays "You Lose..." etc.
    import java.util.Random;//importing utilities//
    import java.util.Scanner;
    
    public class bjjava {
    
    	
    	public static void main(String[] args) {
    		//naming utilities//
    		Random cardDraw = new Random();
    		Scanner hitorstick = new Scanner(System.in);
    		
    		//create Types of variables and name them//
    		int card, total = 0;
    		String deal;
    		
    		
    			//user sees main activate and game start. user dealt a card//
    			System.out.println("Card Total");
    			card = cardDraw.nextInt (10) + 1;
    			System.out.print(card);
    			System.out.print(" ");
    			total =+ card;
    			System.out.println(total);
    				if (total > 21){
    					System.out.print("Bust!!! You got greedy...");//user lost//
    				}else if (total < 21){
    					System.out.println("hit or stick?");
    					deal = hitorstick.next();//user still in. asked how they want to play. scanner called//
    					
    					//switch to control how user's choice effects game//
    					while (total < 21) {
    						switch (deal){
    							case ("hit"): //"hit" repeats the initial 'main' method//
    								System.out.println("Card Total");
    								card = card + cardDraw.nextInt (10) + 1;
    								System.out.print(card);
    								System.out.print(" ");
    								total =+ card;
    								System.out.println(total);
    									if (total > 21){
    										System.out.print("Bust!!! You got greedy...");
    									}else if (total < 21){
    											System.out.println("hit or stick?");
    											deal = hitorstick.next();
    											break;}
    									
    							case ("stick")://"stick" checks 'total' and prints a message//
    									if (total <= 17){
    										System.out.println("You lose...");
    									}else if (total > 17) { //find way to stop >21 winning & busting at same time//
    										System.out.print("You win. :)");
    									}else if (total == 21){
    										System.out.print("Blackjack!!! Have a cigar!"); 
    										break;
    										
    									}
    						}
    					}
    				}
    	}
    }
    

    Most of it seems to be working but there are a couple of problems.
    K, so here are the problems:

    1. When you type "stick" and based on the value of total it displays a message, for example "You lose...", it doesn't just print this out once and then end. It continues printing it over and over again until you terminate the program
    'You Lose... You Lose... You lose...' or 'You win. :) You win. :) You win. :)' over and over again... I want it to just print it once and then end the program.
    Anyone know what's wrong?

    2. When you go bust, it prints out the "Bust..." message, but it also then prints the "You win. :)" message because you are over 21 but also over 17. I thought because I had the "You Win" message in the "stick" case of the Switch, that that message should only print if you have typed "stick"? But apparently not... So how would I go about stopping this happening?

    Here's an example of a run of the program with the second problem happening:
    'Card Total
    10 10
    hit or stick?
    hit
    Card Total
    13 13
    hit or stick?
    hit
    Card Total
    23 23
    Bust!!! You got greedy...You win. :)'



    3. If anyone has any other hints or pointers at all in relation to bad coding going on in it I'd appreciate hearing it too.


    Thanks a million guys.


Comments

  • Closed Accounts Posts: 7,145 ✭✭✭DonkeyStyle \o/


    I think your break statements are breaking out of the switch block rather than the while loop. (You could label the while loop and break out of it by name)
    I'd rethink that while condition too... the game can end without going over 21, so it doesn't make that much sense as a rule. You could replace it with some boolean and toggle it manually when you hit some game ending state.
    I know the temptation to try and make everything short and clever, but it's not cheating to introduce new variables to control what's happening. Especially when you're confused at why something doesn't work, it can be a good way to break things down into more simple terms and re-align what you think is happening with what's actually happening.
    Some ideas...
    Boolean gameIsOver = true;
    Boolean playerWins = false;


  • Moderators, Society & Culture Moderators Posts: 12,523 Mod ✭✭✭✭Amirani


    Good first attempt OP. For issue 2 can you not use have:

    If(total > 17 && total < 21)

    ?


  • Registered Users Posts: 8,163 ✭✭✭batistuta9


    I think you could nest the while loop in the switch statement, specifically inside case ("hit"): as that's where it's needed & include deal is equal to "hit" in the condition. The second case: has no need to be in the while loop

    a bit of rejigging the code is need for that, not much though

    also you could just put all this
    System.out.println(card+" "+total);

    in one line instead of three


  • Closed Accounts Posts: 7,872 ✭✭✭strobe


    Thanks so much for the help guys, really appreciate it.
    I got it working right using the labeled break thing Donkey mentioned and added Batitsuta's idea of using 'System.out.println(card+" "+total);' to cut out the unnecessary repetition of code. And thanks Niall for the idea of using &&, wasn't aware I could do that in the one condition, should come in handy.
    Also fixed a problem I didn't realise I had in the OP where the total was being displayed instead of the individual card number in the card column after you hit. Had 'card = card + cardDraw.nextInt (10) + 1;' instead of just 'card = cardDraw.nextInt (10) + 1;' in the switch for some reason. Hard to keep track of all the little things.
    Also moved the "Blackjack..." message into the "hit" case, rather than the "switch" case, so it automatically displays if you land on 21, as it was a bit redundant asking if you want to hit or stick when you land on 21.
    I'll have a shot at removing the while loop and using the boolean idea when I understand how to use the boolean concept a bit better, still struggling to get my head around how it could replace the while loop thing I have going on...
    If anyone has any other advice or comments I'd love to hear it. :)


    Here's the new code if anyone's interested.
    import java.util.Random;//importing utilities//
    import java.util.Scanner;
    
    public class bjjava {
    
    	
    	public static void main(String[] args) {
    		//naming utilities//
    		Random cardDraw = new Random();
    		Scanner hitorstick = new Scanner(System.in);
    		
    		//create Types of variables and name them//
    		int card, total = 0;
    		String deal;
    		
    		
    			//user sees main activate and game start. user dealt a card//
    			System.out.println("Card Total");
    			card = cardDraw.nextInt (10) + 1;
    			total += card;
    			System.out.println(card+" "+total);
    				if (total > 21){
    					System.out.print("Bust!!! You got greedy...");//user lost//
    				}else if (total < 21){
    					System.out.println("hit or stick?");
    					deal = hitorstick.next();//user still in. asked how they want to play. scanner called//
    					
    					//switch to control how user's choice effects game//
    					endGame: while (total <= 21) {
    						switch (deal){
    							case ("hit")://"hit" repeats the initial 'main' method//
    								System.out.println("Card Total");
    								card = cardDraw.nextInt (10) + 1;
    								total += card;
    								System.out.println(card+" "+total);
    									if (total > 21){
    										System.out.print("Bust!!! You got greedy...");}
    									if (total == 21){
    										System.out.print("Blackjack!!! Have a cigar!");
    										break endGame;}
    									if (total < 21){
    											System.out.println("hit or stick?");
    											deal = hitorstick.next();}
    											break;
    									
    							case ("stick")://"stick" checks 'total' and prints a message//
    									if (total <= 17){
    										System.out.println("You lose...");
    										break endGame;
    									}else if (total > 17) { 
    										System.out.print("You win. :)");
    										break endGame;
    										
    									
    									}
    								}
    						}
    				}
    	}
    }
    

    Thanks again. :)


  • Closed Accounts Posts: 7,145 ✭✭✭DonkeyStyle \o/


    strobe wrote: »
    I'll have a shot at removing the while loop and using the boolean idea when I understand how to use the boolean concept a bit better, still struggling to get my head around how it could replace the while loop thing I have going on...
    Well it wouldn't be to replace the while loop, just the condition in the brackets.
    If you look at something like this:
    if(5 > 3)
    {
      // do something
    }
    
    The statement in the brackets will evaluate to a Boolean true or false.
    So in this case it's the same as:
    if(true)
    {
      // do something
    }
    
    All a Boolean does is store a value of either true or false.
    So you can use it like this:
    Boolean myBool = true;
    if(myBool)
    {
      // do something
    }
    
    So the while example would be:
    Boolean hungry = true;
    while(hungry)
    {
        foodEaten++;
        if(foodEaten >= fullStomach) 
        {
          hungry = false;
        }
        if(aboutToVomit)
        {
            break;
        }
        belch();
    }
    
    The difference between doing this and using break is that execution will continue down to the end of the block before exiting, where as break will jump out immediately.

    It's something you can do to keep track of (and spell out) your intent.
    If you can make your variable and function names accurate to what they are, you can almost write your code in English.
    while(nutsAreAvailable)
    {
      people.getPerson("JimBob").eatFood(nuts);
      //...
    }
    
    (Yes, I'm eating nuts at the moment.)
    You don't even have to do that, you can just write the flow of logic in English separately (AKA Pseudocode). So much of it is about keeping your intent synced up with what's actually happening, so reality-checks are a good place to start if you get lost.

    * I'm not a Java guy, so apologies if any of the above is wrong.


  • Advertisement
  • Registered Users Posts: 8,163 ✭✭✭batistuta9


    If the if statements you write or any statement, only have one statement in them you've no need for the braces
    eg.
    if (total > 21){
      System.out.print("Bust!!! You got greedy...");//user lost//
    }
    
    can be written as 
    
    if (total > 21)
      System.out.print("Bust!!! You got greedy...");//user lost//
    
    your switch statement should also include default: at the end

    & This is something for you to consider:

    the way you're writing code is called 1TBS http://en.wikipedia.org/wiki/Indent_style#Variant:_1TBS this is what you'll see on the Java tutorial's on Oracle's site, most books, videos on the web.
    This is your program (cut down) below in this style
    public class bjjava {
      public static void main(String[] args) {
        //some code here 
        if (total > 21){
          //some code here 
        }else if (total < 21){
          //some code here 
          endGame: while (total <= 21) {
            switch (deal){
              case ("hit"):
                       //some code here  
                       if (total > 21){
    		     System.out.print("Bust!!! You got greedy...");}
    		   if (total == 21){
    		     //some code here }
    		   if (total < 21){
    		     //some code here }
               case ("stick"):
                       if (total <= 17){
    		     //some code here 
    		   }else if (total > 17) { 
    	             //some code here 
                       }
            }
          }  
        }
      }
    }
    

    but you may find this indent style, called Allman style, easier to work with - reading it, etc.
    your program again
    public class bjjava 
    {
      public static void main(String[] args) 
      {
        //some code here 
        if(total > 21)
          System.out.print("Bust!!! You got greedy...");
        else if(total < 21)
        {
          //some code here 
          endGame: while (total <= 21)
          {
            switch (deal)
            {
              case ("hit"):
                       //some code here  
                       if (total > 21)
    		     System.out.print("Bust!!! You got greedy...");
    		   if (total == 21)
                       {
    		     //some code here
                       }
    		   if (total < 21)
                       {
    		     //some code here 
                       }
              case ("stick"):
                       if (total <= 17)
                       {
    		     //some code here 
    		   }
                       else if (total > 17) 
                       { 
    	             //some code here 
                       }
              default: System.out.println("Invalid option entered "); 
                       break;
            }
          }
        }
      }
    }
    

    it's really down to personal preference but i think Allman style is far far easier to read (and of course better :D ), & if you're learning from books, etc. may not be aware of it


  • Closed Accounts Posts: 7,872 ✭✭✭strobe


    Cheers lads.

    Ah yeah I see what you mean now Donkey. I'll have a shot at using it and see how it goes.

    Thanks Batistuta, the Allman indenting thing does look way easier to follow. Had no idea there were different erent styles of doing it. Guess this is one of the great things about actually being able to talk to people that know what they're doing, rather than just learning from books or tutorials.

    I read about the default thing all right. I tried to use it to display a message along the lines of "invalid command" if the user entered something other than "hit" or "stick" but it caused some problems so I just removed it. Should there always be a default?
    As it stands, if you enter "hti" or something the program just ends and nothing happens if you type "hit" or "stick" after that.
    I'll give it another shot when I get a chance to practice a bit more and will post back with the default thing added.

    Thanks. :)


  • Closed Accounts Posts: 799 ✭✭✭Logical_Bear


    If you're using eclipse as your compiler,highlight your code and press ctrl+I and it will automatically indent your code.

    here's a good list of short cuts
    http://www.rossenstoyanchev.org/write/prog/eclipse/eclipse3.html


Advertisement