I've been working on a slot machine program for class and have been having trouble figuring out how to compare the different "slots" on the machine to determine whether or not there are matches and tell the program how to proceed with calculate winnings. I originally thought of storing each result of my random number generator in a variable and then comparing them but am unsure of how to do this. I am unable to use arrays or lists or anything like that unfortunately. Thanks in advance and sorry if my code looks sloppy.
import java.util.*;
//Start Program
public class Slots
{
public static void main(String[] args)
{ //Start Main
//=====Declare Variables=====
int pool = 0,
won = 0,
slot_disp = 0,
slot0 = 0,
slot1 = 0,
slot2 = 0,
slot3 = 0,
slot4 = 0,
matches = 0,
bet = 0;
boolean again = true;
String msg = "",
ans = "";
Scanner key = new Scanner(System.in);
//=====Welcome and Start=====
System.out.println("\t* * * Welcome to SLOTS * * *");
System.out.print("\nEnter amount of money to play: ");
pool = key.nextInt();
while(again)
{
System.out.print("\nEnter your bet: ");
bet = key.nextInt();
while(bet < 0 || bet > pool)//-----Bet Validation-----
{
System.out.println("\tInvalid bet of : " + (double)bet);
System.out.println("\tFunds available: " + (double)pool);
System.out.print("\tRe-Enter bet : ");
bet = key.nextInt();
}
System.out.print(" ");
for(int cntSlot = 0; cntSlot < 5; cntSlot++)
{
Random rand = new Random();
slot_disp = rand.nextInt(5);
//=====Converting Random Number into Slot Display=====
switch(slot)
{
case 0:
msg = "Cherries";
break;
case 1:
msg = "Oranges";
break;
case 2:
msg = "Plums";
break;
case 3:
msg = "Melons";
break;
case 4:
msg = "Bars";
break;
}
System.out.print(msg + " ");
}//-----End Slot Conversion Loop-----
//=====Comparing Slot Output to Determine Winnings=====
switch(matches)
{
case 2:
won = 0;
break;
case 3:
won = bet * 2;
break;
case 4:
won = bet * 3;
break;
case 5:
won = bet * 4;
break;
default:
won = 0;
}
(double)(pool = (pool - bet) + won);
//=====Displaying the Results=====
if(matches == 5)//-----Jackpot-----
{
System.out.println("\n\n * * * You hit the JACKPOT * * *");
System.out.println("You Won: " + won);
}
if(matches > 2 && match < 5)//-----Winner-----
System.out.println("\n\nYou WIN: " + won);
else
System.out.println("\n\n\nNo matches, sorry you lost.");
if(pool <= 0)//-----Game Over-----
{
System.out.println("\n> > > You ran out of money. < < < ");
System.out.println("\nRestart the game to play again");
again = false;
break;
}
else
System.out.println("\nAvailable money: " + (double)pool);
//=====Asking User if they want to Continue=====
if(pool > 0)
{
System.out.print("\nWould you like to play again (y/n): ");
ans = key.next();
}
if(ans.equalsIgnoreCase("y"))
again = true;
else
again = false;
}
System.out.println("Game over, cash out: " + (double)pool);
System.out.println("\nThanks for playing the Slots!");
} //End Main
}
Use an int[] hits = new int[5]; array to store for each value how often it was selected. in the loop increment hits(slot) += 1;. Later, loop over the array to find the maximum.
Related
I'm making a bare-bones Craps simulator with Java on the Eclipse IDE, I'm having a terribly hard time debugging the things that don't seem to indicate any errors in syntax only during the compiling process.
I'm running into this issue when trying to assign a value to the first bet on the "table."
The Pass()method isn't operating as I expected it would, I don't have any immediate error messages however it does not want to compile past this point, which is only line 33 down on the main method.
char answer = keyboard.nextLine().toUpperCase().charAt(0); This line seems to be the largest hurdle in getting all of my methods to operate smoothly throughout.. from what I understand.
I do have a die class but that's proving to be a non issue so I didn't include it in this post.
EDIT: This is the entirety of the program as it stands. I've been tweaking left and right on either end to find the appropriate ways to compile this absolute mess.
Any input is much appreciated. Thank you in Advance.
import java.util.Scanner;
public class Craps {
//Declaring start value of balances
static double totalMoney = 0.00;
static double rollMoney = 0.00;
public static void main(String[] args) {
//Creating Die Objects
Die die1 = new Die();
Die die2 = new Die();
//Beginning of loop
do {
//Displaying the rules for the game
displayMenu();
//Array to hold both Dice and create total for the first roll
//as well as every roll there after
//Initialized 'purses' for the first bets
int dice[] = new int[2];
int intTotal = 0;
int total = 0;
int passBet = 2;
double pass = 0.00;
double dontPass = 0.00;
//Rolling Dice for the first time in the Round
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
intTotal = (dice[0] + dice[1]);
//Assigning Value to Pass/Don't Pass bets
do {
while(Pass() == true) {
try{
pass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
while(dontPass() == true) {
try{
dontPass = getBet();
} catch(NumberFormatException nfe) {
System.out.println("Please answer in this numerical format (0.00)");
}
}
//Display of each individual rolls
//Display of total
//Win-Loss-Continue Play check
switch(intTotal) {
case 7:
case 11:
rollMoney = (pass*passBet);
dontPass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Don't Pass line, better luck next time.");
System.out.println("You have made: " + pass);
System.out.println("Total Earnings: " + totalMoney);
case 2:
case 3:
case 12:
rollMoney = (dontPass*passBet);
pass = 0.00;
System.out.println(dice[0] + " - " + dice[1]);
System.out.println("Very Nice! Pay the Man!");
System.out.println("Sorry Pass line, better luck next time.");
System.out.println("You have made: " + dontPass);
System.out.println("Total Earnings: " + totalMoney);
case 4:
case 5:
case 6:
case 8:
case 9:
case 10:
//"Actual" Game of Craps
do {
double placeBet[] = {1.2, 1.5, 2.0};
int hardBet[] = {7, 9};
int hornBet[] = {15, 30};
//List<Double> place = new ArrayList<Double>();
//List<Double> hard = new ArrayList<Double>();
//List<Double> horn = new ArrayList<Double>();
double place[] = new double[6];
double hard[] = new double[4];
double horn[] = new double[4];
int pBetMax = 6;
int haBetMax = 4;
int hoBetMax = 4;
int pBets[] = new int[pBetMax];
int haBets[] = new int[haBetMax];
int hoBets[] = new int[hoBetMax];
//Gathering Place Bets w/ Location and Value
if(Place() == true) {
pBets = getPlace();
for(int pBetOffset = 1; pBetOffset <= pBetMax; pBetOffset++) {
switch(pBets[pBetOffset]) {
case 4:
place[0] += getBet();
case 5:
place[1] += getBet();
case 6:
place[2] += getBet();
case 8:
place[3] += getBet();
case 9:
place[4] += getBet();
case 10:
place[5] += getBet();
case 0:
break;
}
}
}
//Gathering Hardway Bets w/ Location and Value
if(Hard() == true) {
haBets = getHard();
for(int haBetOffset = 1; haBetOffset <= haBetMax; haBetOffset++) {
switch(haBets[haBetOffset]) {
case 4:
hard[0] += getBet();
case 6:
hard[1] += getBet();
case 8:
hard[2] += getBet();
case 10:
hard[3] += getBet();
case 0:
break;
}
}
}
//Gathering Horn Bets w/ Location and Value
if(Horn() == true) {
hoBets = getHorn();
for(int hoBetOffset = 1; hoBetOffset <= hoBetMax; hoBetOffset++) {
switch(hoBets[hoBetOffset]) {
case 2:
horn[0] += getBet();
case 3:
horn[1] += getBet();
case 11:
horn[2] += getBet();
case 12:
horn[3] += getBet();
case 0:
break;
}
}
}
//Redefining the roll separate from the intRoll
dice = new int[2];
die1.Roll();
dice[0] = die1.getValue();
die2.Roll();
dice[1] = die2.getValue();
total = (dice[0] + dice[1]);
if(intTotal != total) {
switch(total) {
case 11:
rollMoney += (horn[2] * hornBet[1]);
case 2:
rollMoney += (horn[0] * hornBet[2]);
case 3:
rollMoney += (horn[1] * hornBet[1]);
case 12:
rollMoney += (horn[3] * hornBet[2]);
case 4:
if(dice[0]== dice[1]) {rollMoney += (hard[0] * hardBet[1]);}
rollMoney += (place[0] * placeBet[3]);
case 5:
rollMoney += (place[1] * placeBet[2]);
case 6:
if(dice[0]== dice[1]) {rollMoney += (hard[1] * hardBet[2]);}
rollMoney += (place[2] * placeBet[1]);
case 8:
if(dice[0]== dice[1]) {rollMoney += (haBets[2] * hardBet[2]); }
rollMoney += (place[3] * placeBet[1]);
case 9:
rollMoney += (place[4] * placeBet[2]);
case 10:
if(dice[0]== dice[1]) {rollMoney += (haBets[3] * hardBet[1]);}
rollMoney += (place[5] * placeBet[3]);
case 7:
//Wiping the bets clean off the board
pass = 0.00;
place = new double[10];
hard = new double[10];
horn = new double[10];
//Redefining the initial roll for the game
intTotal = 0;
total = 0;
totalMoney += (dontPass * 2);
crapOut();
}
}
}while(crapOut() == true);
}
}while(keepPlaying() == true);
}while(displayMenu() == true);
}
/*
* This method determines if the player will continue after the round is over
*/
public static boolean keepPlaying() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("");
System.out.println("Do you want to roll some more? (Y/N)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
public static boolean crapOut() {
Scanner keyboard = new Scanner(System.in);
boolean playAgain = false;
System.out.println("Crap Out! All Bets are OFF!");
System.out.println("After this roll you now have: $" + rollMoney + " on the board!");
System.out.println("Which bring's your grand total to.. $" + (totalMoney + rollMoney));
System.out.println("Care to make another wager?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
playAgain = answer == 'Y';
keyboard.close();
return playAgain;
}
/*
* This method will assign values to all the bets available to the player
*/
public static double getBet() {
System.out.println("How much would you like to bet?");
Scanner keyboard = new Scanner(System.in);
String bet = keyboard.nextLine();
float num;
num = Float.parseFloat(bet);
keyboard.close();
return num;
}
/*
* This method will ask if the player would like to Accept or Press their bet
*/
public static boolean pressBet(int bet) {
Scanner keyboard = new Scanner(System.in);
boolean press = false;
System.out.println("Press your bet? (Double your initial wager)");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
press = answer == 'Y';
bet = bet * 2;
keyboard.close();
return press;
}
/*
* Methods to check if play would like to place wager
* Methods to assign those bets to appropriate places on the table
*/
public static boolean Pass() {
Scanner keyboard = new Scanner(System.in);
boolean pass = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
pass = answer == 'y';
keyboard.close();
return pass;
}
public static boolean dontPass() {
Scanner keyboard = new Scanner(System.in);
boolean dontPass = false;
System.out.println("Would you like to make a Don't Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
dontPass = answer == 'Y';
keyboard.close();
return dontPass;
}
public static boolean Place() {
Scanner keyboard = new Scanner(System.in);
boolean place = false;
System.out.println("Would you like to make a Place Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
place = answer == 'Y';
keyboard.close();
return place;
}
public static int[] getPlace() {
int counter = 1;
int max = 6;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[6];
do {
System.out.println("Make selections from the numbers (4, 5, 6, 8, 9, 10), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Horn() {
Scanner keyboard = new Scanner(System.in);
boolean horn = false;
System.out.println("Would you like to make a Pass Line Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
horn = answer == 'Y';
keyboard.close();
return horn;
}
public static int[] getHorn() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make selections from the numbers (2, 3, 11, 12), Enter 0 to exit.");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
public static boolean Hard() {
Scanner keyboard = new Scanner(System.in);
boolean hard = false;
System.out.println("Would you like to make a Hardway Bet?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
hard = answer == 'Y';
keyboard.close();
return hard;
}
public static int[] getHard() {
int counter = 1;
int max = 4;
Scanner keyboard = new Scanner(System.in);
int[] select = new int[4];
do {
System.out.println("Make a selection from the numbers (4 (2&2), 6 (3&3), 8(4&4), 10(5&5)");
System.out.println("Enter bet and hit return for each selection.");
select[counter] = keyboard.nextInt();
counter++;
} while(counter <= max || select[counter] != 0);
keyboard.close();
return select;
}
/*
* Method to display rules and parameters of game prior to playing
*/
public static boolean displayMenu() {
System.out.println("Welcome to the Crosby Casino!");
System.out.println("The Game is Craps, Rules Are:");
System.out.println("If a 7 or 11 is the first roll on the table,");
System.out.println("Pass bets get paid on the first roll!");
System.out.println("If a 2, 3, or 12 is the first roll on the table, ");
System.out.println("Don't pass bets get paid on the first roll!");
System.out.println("If any other value is rolled, the game begins..");
System.out.println("Pass bets believe whatever other value was rolled will appear before the next 7 does.");
System.out.println("Don't Pass bets believe that the 7 will appear before the initial roll's value is shown again.");
System.out.println("During the duration of the roll you can make up to 3 separate side bets");
System.out.println("'Place bets' - (2, 5, 6, 8, 9, 10) Which pay out every time these numbers appear following the initial roll");
System.out.println("'Hard bets' - (4, 6, 8, 10) Which has the most coverage of all potential outcomes");
System.out.println(" & 'Horn bets' - (2, 3, 11, 12) The best payout odds on the table");
System.out.println("The table minimum is $5.00 to play");
System.out.println("All side bet minimums are $1.00 to play");
Scanner keyboard = new Scanner(System.in);
boolean menu = false;
System.out.println("Would you like play?");
char answer = keyboard.nextLine().toUpperCase().charAt(0);
menu = answer == 'Y';
keyboard.close();
return menu;
}
}
Java arrays are 0-origin. Basically, that means that the first element in arrays have an index of 0, not 1, as your dice array shows. Thus, you need to replace dice[1] and dice[2] with dice[0] and dice[1], respectively.
EDIT Based on new info from comments:
This sounds like a new error than the AIOOBE that you previously described. The issue with your code is that you need to ensure that you use Scanner's hasNextLine() method before calling the nextLine() method. Essentially, you are calling nextLine() when there is no "next line", causing the NoSuchElementException.
I am building a war card game for an assignment I have the game built and it is working but I am running into the issue such as card 10 jack of spades is less in value as say card 23 the jack of hearts. Looking for advice about the best way to be able to compare the cards to see if they are equal.
Below is the code I have so far:
import java.util.Random;
import java.util.Scanner;
public class WarGame {
public static void main(String a[]) {
DeckOfCards d = new DeckOfCards();
int input = 0;
int computer = 0;
int you = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
while (input != 2) {
if (input == 1) {
System.out.print("\n\nEnter the value of the card:");
int card = sc.nextInt();
if (card >= 0 && card <= 51) {
int systemCard = d.computerTurn(card);
System.out.println("Your card - " + d.inputCard(card));
System.out.println("Computer card - " + d.inputCard(systemCard));
if(systemCard > card)
++computer;
else
++you;
System.out.println("The winner is " + (systemCard > card ? "Computer" : "You"));
} else {
System.out.println("Invalid card");
}
}
else {
System.out.println("That is an invalid selection please choose 1 or 2.");
}
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
}
System.out.println("Total Wins by Computer: "+ computer);
System.out.println("Total Wins by You: "+ you);
if (computer > you)
System.out.println("Computer is the champion");
else if (computer == you)
System.out.println("Its a Tie");
else
System.out.println("You are the champion");
}
}
class DeckOfCards {
String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
Random ran = new Random();
int systemWin = 0;
int playerWin = 0;
String inputCard(int card) {
int suit = card / 13; //assigning suit to your card
int rank = card % 13; //Assigning rank to your card
String out = "";
switch (rank) { //Setting up face cards for the cases
case 0:
out = "Ace of " + suits[suit];
break;
case 10:
out = "Jack of " + suits[suit];
break;
case 11:
out = "Queen of " + suits[suit];
break;
case 12:
out = "King of " + suits[suit];
break;
default:
out = rank + 1 + " of " + suits[suit]; //Adding one to remainder so it will go from 2-10 instead of 1-9
break;
}
return out;
}
int computerTurn(int playerRank) { //Keeping track of the wins for computer and player
int systemRank = this.ran.nextInt(51);
if (systemRank > playerRank)
systemWin++;
else
playerWin++;
return systemRank;
}
}
I think you're comparing the index to your deck rather than the card values themselves. If I'm understanding, you want to compare d.inputCard(card) with d.inputCard(systemCard) instead of card with systemCard. But of course, that's a String. Having a hard time following the code :-).
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
String playAgainMsg = "Would you like to play again?";
String pickCategoryMsg = "You've tried all the words in this category!\nWould you like to choose another category?";
int winCounter = 0, loseCounter = 0, score = 0;
String[] words;
int attempts = 0;
String wordToGuess;
boolean playCategory = true, playGame = true;
int totalCounter = 0, counter;
while (playCategory && playGame)
{
while (playCategory && playGame) {
words = getWords();
counter = 0;
while (playGame && counter < words.length) {
wordToGuess = words[counter++];
if (playHangman(wordToGuess)) {
winCounter++;
System.out.println("You win! You have won " + winCounter + " game(s)." + " You have lost " + loseCounter + " game(s).");
} else {
loseCounter++;
System.out.println("You lose! You have lost " + loseCounter + " game(s)." + " You have won " + winCounter + " game(s).");
}
if (counter < words.length) playGame = askYesNoQuestion(playAgainMsg);
}
if (playGame) playCategory = askYesNoQuestion(pickCategoryMsg);
}
}
}
public static boolean playHangman(String wordToGuess) {
String[] computerWord = new String[wordToGuess.length()];
String[] wordWithDashes = new String[wordToGuess.length()];
for (int i = 0; i < computerWord.length; i++) {
computerWord[i] = wordToGuess.substring(i, i+1);
wordWithDashes[i] = "_";
}
Scanner in = new Scanner(System.in);
int attempts = 0, maxAttempts = 7;
boolean won = false;
int points = 0;
while (attempts < maxAttempts && !won) {
String displayWord = "";
for (String s : wordWithDashes) displayWord += " " + s;
System.out.println("\nWord is:" + displayWord);
System.out.print("\nEnter a letter or guess the whole word: ");
String guess = in.nextLine().toLowerCase();
if (guess.length() > 1 && guess.equals(wordToGuess)) {
won = true;
} else if (wordToGuess.indexOf(guess) != -1) {
boolean dashes = false;
for (int i = 0; i < computerWord.length; i++) {
if (computerWord[i].equals(guess)) wordWithDashes[i] = guess;
else if (wordWithDashes[i].equals("_")) dashes = true;
}
won = !dashes; // If there are no dashes left, the whole word has been guessed
} else {
drawHangmanDiagram(attempts);
System.out.println("You've used " + ++attempts + " out of " + maxAttempts + " attempts.");
}
}
int score = 0;
score = scoreGame(attempts);
System.out.println("Your score is: " + score);
return won;
}
//should take in a failure int from the main method that increments after every failed attempt
public static void drawHangmanDiagram(int failure)
{
if (failure == 0)
System.out.println("\t+--+\n\t| |\n\t|\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 1)
System.out.println("\t+--+\n\t| |\n\t| #\n\t|\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 2)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 3)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| / \\\n\t|\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 4)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t|\n\t|\n\t|\n\t+--");
else if (failure == 5)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| /\n\t|\n\t|\n\t+--");
else if (failure == 6)
System.out.println("\t+--+\n\t| |\n\t| #\n\t| /|\\\n\t| |\n\t| / \\\n\t|\n\t|\n\t+--");
}
// Asks user a yes/no question, ensures valid input
public static boolean askYesNoQuestion(String message) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println(message + " (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
public static boolean askForCategory(int category) {
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("\nWould you like to play again? (Y/N)");
answer = in.nextLine().toLowerCase();
if (answer.matches("[yn]")) validAnswer = true;
else System.out.println("Invalid input! Enter 'Y' or 'N'.");
} while (!validAnswer);
return answer.equals("y");
}
// Asks the user to pick a category
public static String[] getWords() {
String[] programming = {"java", "pascal", "python", "javascript", "fortran", "cobol"};
String[] sports = {"gymnastics", "badminton", "athletics", "soccer", "curling", "snooker", "hurling", "gaelic", "football", "darts"};
String[] result = {""};
Scanner in = new Scanner(System.in);
boolean validAnswer = false;
String answer;
do {
System.out.println("Pick a category:\n1. Programming\n2. Sports");
answer = in.nextLine().toLowerCase();
if (answer.matches("[1-2]")) validAnswer = true;
else System.out.println("Invalid input! Enter the number of the category you want.");
} while (!validAnswer);
int selection = Integer.parseInt(answer);
switch (selection) {
case 1: result = randomOrder(programming); break;
case 2: result = randomOrder(sports); break;
}
return result;
}
// Sorts a String array in random order
public static String[] randomOrder(String[] array) {
int[] order = uniqueRandoms(array.length);
String[] result = new String[array.length];
for (int i = 0; i < order.length; i++) {
result[i] = array[order[i]];
}
return result;
}
// Generates an array of n random numbers from 0 to n-1
public static int[] uniqueRandoms(int n) {
int[] array = new int[n];
int random, duplicateIndex;
for (int i = 0; i < n; ) {
random = (int) (Math.random() * n);
array[i] = random;
for (duplicateIndex = 0; array[duplicateIndex] != random; duplicateIndex++);
if (duplicateIndex == i) i++;
}
return array;
}
public static int scoreGame(int attempts)
{
int score = 0;
switch (attempts)
{
case 0: score = 70; break;
case 1: score = 60; break;
case 2: score = 50; break;
case 3: score = 40; break;
case 4: score = 30; break;
case 5: score = 20; break;
case 6: score = 10; break;
case 7: score = 0; break;
}
return score;
}
}
I have got it working so that it keeps count of the games won and lost, as well as assigning a score based on the amount of attempts/lives saved but I haven't been able to find a way to get it to keep a total score for all of the games played. Each game unfortunately has a seperate score. If anyone can advise me on a way of doing this, it would be greatly appreciated.
Create an int totalScore variable where winCounter, loseCounter and score are defined. Then increment it after each call to scoreGame()
score = scoreGame(attempts);
totalScore += score;
System.out.println("Your score is: " + score);
If you want to permanently save statistics between sessions then it's a whole nother story. You would need to write your scores to a file after each round and then start your program by reading this score file. It's hardly impossible, but requires a bit more code.
EDIT: I have some corrections as an answer. I needed to use another do-while loop for different scenarios in the slot machine. I have figured out the answer to this particular question and have posted the answer for anyone who would like to use this for help.
I have a single do while loop that will not finish. In order to enter the do while loop, I need to enter a number. It will not start unless the user enters something- it will give a mismatch error if one enters a letter which is understandable, but how can I get into the loop without the user entering anything?
Also, would putting in another do loop solve the problem of it not fully running? I'm confused as to the logic of it and my pseudocode is wrong. Thank you.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot2
{
public static void main(String[] args) throws IOException
{
int number;
System.out.println ("Welcome to the Slot Machine Simulator!");
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
break;
}
if (option == 1)
{
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
System.out.print ("\nBefore the game begins, please enter your name: ");
username = keyboard.next( );
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
do **//you have to enter a number here to get the 1st print statement,this is the error**
{
double bet = keyboard.nextDouble();
bet = 0.0;
userTotal = startingTotal - bet;
System.out.print ("You currently have: $%.2f" + startingTotal + "\nHow much would you like to bet?"); **//this is the part of the loop that works**
double winnings = 0.0;
double userFinalTotal = 0.0;
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("-------------------------------");
System.out.println ("" + firstSlot + " " + secondSlot + " " + thirdSlot);
System.out.print ("-------------------------------");
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2fn", userFinalTotal);
}
else
{
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
if ((bet < 0) || (userFinalTotal <= 0))
{
break;
}
while (bet > userFinalTotal)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
} while (userTotal > 0);
}
}
}
Try changing username = keyboard.next( ); to username = keyboard.nextLine( );, I am sure it will work.
There is nothing wrong with your do-while loop.
On top of that, you shouldn't declare these variables inside your while loop.
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
I have a printwriter statement in a do-while loop in order to print the scores of every user that plays the slot machine. However, I think because of this scores print multiple times when it says to view scores (option 2). Is this because of the variable used, or the fact it is in a do-while loop?
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot3
{
public static void main(String[] args) throws IOException
{
System.out.println ("Welcome to the Slot Machine Simulator!");
int option = 0;
//if the user selects a 1 or 2 (does not want to exit) then this loop will run
do
{
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
keyboard.nextLine();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
keyboard.nextLine();
}
//this will occur if the user selects 1 to play the game
if (option == 1)
{
double money = 100.00;
double bet = 0.00;
double winnings = 0.00;
double score = 0.00;
int count = 0;
System.out.print ("\nBefore the game begins, please enter your name: ");
String username = keyboard.nextLine();
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
System.out.printf("\nYou currently have $%.2f.", 100.00);
do
{
System.out.printf("\n\nHow much would you like to bet? ");
bet = keyboard.nextDouble();
if ((bet < 0) || (money <= 0))
{
break;
}
while (bet > money)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
//create random numbers
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("\n-------------------------------");
System.out.printf ("%-12s%-10s%5s\n", firstSlot , secondSlot , thirdSlot);
System.out.print ("\n-------------------------------");
//check how many of the slots match to calculate the winnings
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else
{
winnings = bet * 0;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
} while ((bet > 0) && (money > 0));
FileWriter fwriter = new FileWriter("scores.txt", true);
PrintWriter outputWriter = new PrintWriter(fwriter);
outputWriter.printf("\n\n%1s%15s" , "Name" , "Score");
outputWriter.printf ("\n\n%1s%15s" , "----" , "-----");
outputWriter.printf ("\n\n%1s%15s" , username , score);
outputWriter.close();
System.out.println("\n\nGame over! Your score has been written to scores.txt, " + username + "!");
} //end of actions for select option 1
//option 2 user wants to read their scores
if (option == 2)
{
File myFile = new File("scores.txt");
//if there are no scores to read
if (!myFile.exists())
{
System.out.println("There are no scores to display at this time.");
continue;
}
File file = new File("scores.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String username = inputFile.nextLine();
System.out.println(username);
}
inputFile.close();
} //close option 2
} while (option != 3); //close 1st do-while loop
if (option == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}
Int counter = 0, input = 0;
While(counter < 10 && input = 0)
{
Thread.sleep(1000);
Counter++;
input = Scan.nextInt()
}
Not the greatest code I did this from my phone so
For this code, I want to simulate a slot machine and put the username and scores of the games onto a text file titled scores.txt so that if the user selects option 2 they can view their scores.
However, I receive many errors on my FileWriter statement (line is towards the end and marked with a comment), particulary one that I don't understand called unmappable character for encoding CP1252. From everywhere I have checked, I see this error when someone uses a different character like a Japanese character- so why would an error like this come about? I've looked at examples of code but I have not yet learned stream, try and catch, or buffer.
Using filewriter and printwriter can someone explain to me how to create a filewriter object and pass it to a printwriter object correctly, as well as how to correctly read data from that file (scores.txt). Thanks so much in advance, and sorry if this is a simple error.
Specific area of problem:
File file = new File(“scores.txt”); //illegal start of expression
if (!file.exists())
{
file.createNewFile();
}
Scanner inputFile = new Scanner(file);
String line = inputReader.nextLine();
FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252,
PrintWriter outputWriter = new PrintWriter(file);
outputFile.println(username);
outputFile.println(userFinalTotal);
}
else if (option == 2)
{
if (file.exists())
{
while (inputFile.hasNext())
{
username = inputFile.nextLine();
System.out.println ("Name\n------\n" + name + "\n");
userFinaltotal = inputFile.nextDouble();
System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
System.out.println();
inputReader.close();
}
Here is the full program to see where the variables come from.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class SlotsMachine
{
public static void main(String[] args) throws IOException
{
int number;
System.out.println ("Welcome to the Slot Machine Simulator!");
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
break;
}
if (option == 1)
{
String username;
double startingTotal = 100.0;
double userTotal = startingTotal;
System.out.print ("\nBefore the game begins, please enter your name: ");
username = keyboard.next( );
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
do
{
double bet = keyboard.nextDouble();
bet = 0.0;
userTotal = startingTotal - bet;
System.out.print ("You currently have: " + startingTotal + "\nHow much would you like to bet?");
double winnings = 0.0;
double userFinalTotal = 0.0;
if ((bet < 0) || (userFinalTotal <= 0))
{
break;
}
while (bet > userFinalTotal)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
Random generator = new Random();
int slot1 = generator.nextInt(6);
keyboard.nextLine();
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("-------------------------------");
System.out.println ("" + firstSlot + " " + secondSlot + " " + thirdSlot);
System.out.print ("-------------------------------");
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
userFinalTotal = userTotal + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2fn", userFinalTotal);
}
else
{
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf ("\nYou currently have: $%.2f", userFinalTotal);
}
} while (userTotal > 0);
File file = new File(“scores.txt”); //illegal start of expression
if (!file.exists())
{
file.createNewFile();
}
Scanner inputFile = new Scanner(file);
String line = inputReader.nextLine();
FileWriter fwriter = new FileWriter(“scores.txt”, true); //this is where the error CP1252
PrintWriter outputWriter = new PrintWriter(file);
outputFile.println(username);
outputFile.println(userFinalTotal);
}
else if (option == 2)
{
if (file.exists())
{
while (inputFile.hasNext())
{
username = inputFile.nextLine();
System.out.println ("Name\n------\n" + name + "\n");
userFinaltotal = inputFile.nextDouble();
System.out.printf("Scores\n------\n$%.2f\n", userFinalTotal);
System.out.println();
inputReader.close();
}
}
else
{
System.out.println("There are no scores to display at this time.");
}
System.out.println("Actions:");
System.out.print("1. Start a new game\n2. View scores\n3. Exit ");
System.out.println("Please select an action: ");
option = keyboard.nextInt();
}
else if (number == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}
It compiles now, the only problem is that it prints the scores multiple times.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Slot3
{
public static void main(String[] args) throws IOException
{
System.out.println ("Welcome to the Slot Machine Simulator!");
int option = 0;
//if the user selects a 1 or 2 (does not want to exit) then this loop will run
do
{
System.out.println ("\nActions\n1. Start a new game\n2. Scores\n3. Exit");
System.out.print ("\nPlease select an action: ");
Scanner keyboard = new Scanner(System.in);
option = keyboard.nextInt();
keyboard.nextLine();
while (option != 1 && option != 2 && option != 3)
{
System.out.print ("\nThat is not an option. Please select an item number between 1-3: ");
option = keyboard.nextInt();
keyboard.nextLine();
}
//this will occur if the user selects 1 to play the game
if (option == 1)
{
double money = 100.00;
double bet = 0.00;
double winnings = 0.00;
double score = 0.00;
int count = 0;
System.out.print ("\nBefore the game begins, please enter your name: ");
String username = keyboard.nextLine();
System.out.print ("\nGame start! You will begin with $100.00. Enter a negative value to quit the game. Good luck, " + username + "!");
System.out.printf("\nYou currently have $%.2f.", 100.00);
do
{
System.out.printf("\n\nHow much would you like to bet? ");
bet = keyboard.nextDouble();
if ((bet < 0) || (money <= 0))
{
break;
}
while (bet > money)
{
System.out.print("\nYour bet is greater than your current total. Please enter a valid amount: ");
bet = keyboard.nextDouble();
}
//create random numbers
Random generator = new Random();
int slot1 = generator.nextInt(6);
int slot2 = generator.nextInt(6);
int slot3 = generator.nextInt(6);
String firstSlot = "";
switch (slot1)
{
case 0:
firstSlot = "Cherries";
break;
case 1:
firstSlot = "Oranges";
break;
case 2:
firstSlot = "Plums";
break;
case 3:
firstSlot = "Bells";
break;
case 4:
firstSlot = "Melons";
break;
case 5:
firstSlot = "Bars";
break;
}
String secondSlot = "";
switch (slot2)
{
case 0:
secondSlot = "Cherries";
break;
case 1:
secondSlot = "Oranges";
break;
case 2:
secondSlot = "Plums";
break;
case 3:
secondSlot = "Bells";
break;
case 4:
secondSlot = "Melons";
break;
case 5:
secondSlot = "Bars";
break;
}
String thirdSlot = "";
switch (slot3)
{
case 0:
thirdSlot = "Cherries";
break;
case 1:
thirdSlot = "Oranges";
break;
case 2:
thirdSlot = "Plums";
break;
case 3:
thirdSlot = "Bells";
break;
case 4:
thirdSlot = "Melons";
break;
case 5:
thirdSlot = "Bars";
break;
}
System.out.println ("\n-------------------------------");
System.out.printf ("%-12s%-10s%5s\n", firstSlot , secondSlot , thirdSlot);
System.out.print ("\n-------------------------------");
//check how many of the slots match to calculate the winnings
if (slot1 == slot2 && slot1 == slot3)
{
winnings = bet * 3;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 3. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else if ((slot1 == slot2 && slot2 != slot3) || (slot1 == slot3 && slot1 != slot2) || (slot2 == slot3 && slot3 != slot1))
{
winnings = bet * 2;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 2. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
else
{
winnings = bet * 0;
money -= bet;
score = money + winnings;
System.out.printf ("\nNumber of matches: 0. You win: $%.2f", winnings);
System.out.printf("\nYou currently have: $%.2f", score);
}
} while ((bet > 0) && (money > 0));
FileWriter fwriter = new FileWriter("scores.txt", true);
PrintWriter outputWriter = new PrintWriter(fwriter);
outputWriter.printf("\n\n%1s%15s" , "Name" , "Score");
outputWriter.printf ("\n\n%1s%15s" , "----" , "-----");
outputWriter.printf ("\n\n%1s%15s" , username , score);
outputWriter.close();
System.out.println("\n\nGame over! Your score has been written to scores.txt, " + username + "!");
} //end of actions for select option 1
//option 2 user wants to read their scores
if (option == 2)
{
File myFile = new File("scores.txt");
//if there are no scores to read
if (!myFile.exists())
{
System.out.println("There are no scores to display at this time.");
continue;
}
File file = new File("scores.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String username = inputFile.nextLine();
System.out.println(username);
}
inputFile.close();
} //close option 2
} while (option != 3); //close 1st do-while loop
if (option == 3)
{
System.out.print ("\nGoodbye!");
System.exit(0);
}
}
}