Aannnaaaa
Aannnaaaa

Reputation: 1

Java Slot Machine Program - Now what to correct?

I apologize if this didn't format correctly, I tried to do it right. I need advice on what is wrong, out of order, incorrectly written... Can't get past the compiler yet, every "fix" seems to generate more errors.

I was trying to write a while loop in the main that runs as long as the user indicates they want to play

In the while loop I called 3 methods:

  1. generate random number to pull the corresponding Case # out of the switch statement to get the 3 items using a for loop

  2. to calculate winnings based on the match and the bet then display

  3. find out if the player wanted to keep playing to keep the while loop going or to shut it sown,

I will be glad of any advice,

The problem is pasted at the top of the code so that what I'm working on will be more clear. Thank you!

This is the problem:

~Slot Machine: 
A slot machine is a gambling device into which the user inserts money and then pulls a lever or presses a button. 
The slot machine then displays a set of random images. If two or more of the images match, the user wins an amount of money, 
which the slot machine dispenses back to the user.

Design a program that simulates a slot machine. When the program runs, it should do the following:

 *   Ask the user to enter the amount of money she wants to insert into the slot machine.
 *   Instead of displaying images, the program will randomly select a word from the following list: Cherries, Oranges, Plums, Bells, Melons, Bars. 
     The program will select and display a word from this list three times (like the three columns in a real slot machine).
 *   If none of the randomly selected words match, the program will inform the user that she has won $0. 
 *   If two of the words match, the program will inform the user that she has won twice the amount wagered in the first step. 
 *   If all three of the words match, the program will inform the user that she has won three times the amount entered.
 *   The program will ask whether the user wants to play again. 
      If so, these steps are repeated. 
      If not, the program displays the total amount of money entered into the slot machine and the total amount won.
*/

This is revised code with the compiler errors commented out next tot the line number for which they appeat

import java.util.Scanner;
import java.util.Random;

public class SlotMachineHWCH6
{

   public static void Main(String[] args)
   {
      //declarations
      Scanner keyboard = new Scanner(System.in);  //for user input
      //string slotMachine;   //don't know if will be used
      //double initialPlayerBet;  //first bet
      double playerBet = 0;  //subsequent bets
      //double totalPlayerBets; //total amount user spent in the slot machine
      double totalWinnings = 0;   //total amount won
      double tripleWin = 0;   //amount won when all 3 match
      double doubleWin = 0;   //amount won when 2 match

      String spin, spin1, spin2, spin3;    
      int i;                       //counter variable
      String no;
      String yes;       
      boolean keepPlaying;  //response to prompt to continue playing

      System.out.println("Slot machine payout: 3 items match - win triple your bet. 2 items match = win double your bet. No match, no win.\n");

48     while (keepPlaying)  /*SlotMachineHWCH6.java:48: error: variable keepPlaying might not have been initialized
      while (keepPlaying)*/

     {
         System.out.println("Enter your bet");
         playerBet = keyboard.nextDouble();

55         for (i = 1; i <= 3; i++)/*SlotMachineHWCH6.java:55: error: variable spin might not have been initialized 
         getSlotItems(spin);*/
                       ^

         {       
         getSlotItems(spin); /*error: variable spin might not have been initialized*/
          getSlotItems(spin);

56         System.out.println(spin1 + "," + spin2 + "," + spin3); /*56: error: variable spin1 might not have been initialized
          System.out.println(spin1 + "," + spin2 + "," + spin3); + same for spin2  and spin3*/

         }

59            spinWinnings(spin1, spin2, spin3);/*59: error: variable spin1 might not have been initialized
             spinWinnings(spin1, spin2, spin3); and there are the same messages for spin2, spin3 */

60            playAgain(yes, no); /* 60: error: variable no might not have been initialized*/
             playAgain(yes, no);   /*same error for 'yes'*/
                            ^

     }
    }


   //get the random 3 slot items out of 6 possible
   public static String getSlotItems(String spin)
   {
      //declarations
      Random rand = new Random();  //random number generator



      //map a random number to the items in the list
       switch(rand.nextInt(6))
      {
      case 0:
         spin = "Cherries";
         System.out.println("Cherries");
         break;

      case 1:
         spin = "Oranges";
         System.out.println("Oranges");
         break;

      case 2:
         spin = "Plums";
         System.out.println("Plums");
         break;

      case 3:
         spin = "Bells";
         System.out.println("Bells");
         break;

      case 4:
         spin = "Melons";
         System.out.println("Melons");
         break;

      case 5:
         spin = "Bars";
         System.out.println("Bars");
         break;

      default:
         System.out.println("ERROR ERROR ERROR");
         break;
      }
      return spin;

   }

   public static void spinWinnings(String spin1, String spin2, String spin3)
   {
      if (spin1 == spin2 && spin2 == spin3)
      {

          //double doubleWin;  
 125      double tripleWin;   /*variable playerBet might not have been initialized
       tripleWin = playerBet * TRIPLE;   /*variable playerBet might not have been initialized
           tripleWin = playerBet * TRIPLE;*/
                       ^

                       ^

          double playerBet;
          double newTotal;
          final int TRIPLE = 3; // to calculate winnings for 3 matches

          tripleWin = playerBet * TRIPLE;
          newTotal = playerBet + tripleWin;
          System.out.println("3 match, you won $ "+ tripleWin);
          System.out.println("You have $ " + newTotal);
          newTotal++;
      }          
      else if (spin1 == spin2 || spin2 == spin3 || spin3 == spin1)
      {
          double doubleWin;
          double playerBet;
          double newTotal;
          final int DOUBLE = 2; // to calculate winnings for 2 matches



 140      doubleWin = playerBet * DOUBLE;     /*140: error: variable playerBet might not have been initialized
           doubleWin = playerBet * DOUBLE;*/
          newTotal = playerBet + doubleWin;
          System.out.println("2 match, you won $ "+ doubleWin);          
          System.out.println("You have $ " + newTotal);
          newTotal++;
      }    
      else
      {
         System.out.println("None match, you won absolutely nothing.");
      }
   }

   public static boolean playAgain(String yes, String no)
   {
      Scanner keyboard = new Scanner(System.in);
      String playSomeMore;
      ////String yes;
     // String no;

      System.out.println("Play again? Enter yes or no.");
      playSomeMore = keyboard.nextLine();

      if (playSomeMore.equals("yes"))
      {
         return true;
      }
      else
      {
         return false;
      }  
   }

I don't understand why I had to declare variables within if and else statements...are they considered methods?

Does this look like it is even close to running as it should?

Some of the things I have commented out I will delete once it is working, some were for variable I thought I needed but didn't use, some of them I was moving around to see if I had them in the wrong or right location.

Upvotes: 0

Views: 8182

Answers (5)

D.T.F.
D.T.F.

Reputation: 68

The errors are coming from the fact that the variables are at a null value when they are used in the code. The main loop won't start because you have "boolean keepPlaying;," which is good as a naming of the variable, but it assigns it to a null value. So, when you ask java to check whether keepPlaying is true, it has no idea what keepPlaying is. You should set keepPlaying to true (boolean keepPlaying = true;) at the top, so the while loop will start. Then, when you want the game to end, just set it to false. Luckily, your errors are easily fixed! :) I know the feeling of frustration when you can't figure something, out, though.

As far as the other errors, it's the same issue. So, for those, just set them to a dummy value, like ints to 0 and strings to "". It's okay to set them like that for now because they'll be changed when the game starts.

I would also like to point out that it might be a good idea to keep the game outside the main method. Initialize all the variables in the class constructor, then make a new object in the main method(slotMachine game = new slotMachine()). You could then have a start() method (call this in the main method: slotMachine.start()) which would set keepPlaying to true and call the run method. The reason I say this is because it keeps away from static variables. Right now every variable you have declared is static because it's under the static void main. This is just a preference, but I hate having to work around static variables, so I normally have a class called Main with the main void that makes the Game class, which has the runtime.

Good job, and good luck to you!

Upvotes: 0

avgvstvs
avgvstvs

Reputation: 6325

As someone else already posted the issue with the assignment, I'm going to answer this question:

"I don't understand why I had to declare variables within if and else statements...are they considered methods?"

This is called "lexical scoping" and no, if/else blocks are not methods, but like methods, an if/else, switch, for loop, etc. all are treated with their own local variable resolution.

Upvotes: 1

jpw
jpw

Reputation: 44911

First, in your main method the condition to check whether to keep playing should be just while (keepPlaying) as what you've got at the moment is an assignement = and not an equality check ==.

Also, the keepPlaying method should be changed to something like this:

public static boolean keepPlaying()
   {
      Scanner keyboard = new Scanner(System.in);
      String playAgain;

      System.out.println("Play again? Enter yes or no.");
      playAgain = keyboard.nextLine();

      return (playAgain.equals("yes"));
   }

and you want to call it with keepPlaying = keepPlaying(), but it would also be a good idea to rename it as you already have a variable with that name.

Upvotes: 0

slim
slim

Reputation: 41271

Methods, if statements, for loops are all examples of blocks, and almost all blocks work the same as far as variable scope is concerned.

A variable is visible to the block it is in, and to blocks inside that block.

A variable is not visible to the block outside the block it is in.

You don't even need a method, if, for etc. to define a block -- you can just write a block on its own, to create a scope just because you want one.

{
    // 'var' is not visible here
    {
        int var = 5;
        // var is visible here
        {
             // var is also visible here
        }
    }
}

Always try to declare variables in the smallest scope you can. This means that at any particular place in the code, there are fewer variables visible, and therefore less opportunity to confuse the programmer.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234865

Excepting all the syntax and looping errors which, with a bit of Googling, reading and patience, you'll eventually fix (pay special attention to while (keepPlaying = true) which yields an infinite loop due to assignment), the only serious problem you have is your use of the random number generator:

  Random rand = new Random();  //random number generator

This creates a new generator every time from scratch which completely ruins the statistical properties of the generator. The best thing to do is to have this random number generator as a field in your class.

Upvotes: 1

Related Questions