Craps Project - Debugs for non apparent syntax errors - java

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.

Related

Decrement by a certain amount on java

i'm trying to create a program where the number that the user has input would decrease by a certain amount. something that would like this:
Update by (Increment/Decrement):decrement
Enter starting number:15
Enter update number:3
Enter end number:3
loop#1 value=15
loop#2 value=12
the end number is where the loop would stop and the update number is how much the starting number should decrement by. so far this is the code I have and I'm stuck on how to keep the loop going until the end number.
package jaba;
import java.util.Scanner;
public class loop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String Decrement = scan.nextLine();
System.out.print("Enter starting number:");
String number = scan.nextLine();
System.out.print("Enter update number:");
String upnumber = scan.nextLine();
System.out.print("Enter end number:");
String endnumber = scan.nextLine();
int i,j;
i = 15;
j = 1;
do {
System.out.println("loop#" +j+ "\tvalue="+i);
j++;
}while(i<15);
i = i-3;
System.out.println("loop#" +j+ "\tvalue="+i);
};
}
how about something like this:
public class loop {
public enum Operation {INCREMENT, DECREMENT, INVALID}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Update by (Increment/Decrement):");
String operationString = scan.nextLine();
System.out.print("Enter starting number:");
String numberString = scan.nextLine();
System.out.print("Enter update number:");
String upnumberString = scan.nextLine();
System.out.print("Enter end number:");
String endnumberString = scan.nextLine();
// Determine and parse stuff
int startNumber = Integer.parseInt(numberString);
int updateNumber = Integer.parseInt(upnumberString);
int endNumber = Integer.parseInt(endnumberString);
// Parse operation, but assume invalid operation
Operation operation = Operation.INVALID;
if (operationString.equalsIgnoreCase("increment")) {
operation = Operation.INCREMENT;
} else if (operationString.equalsIgnoreCase("decrement")) {
operation = Operation.DECREMENT;
}
// now do the "meat" of the assignment
int loopNumber = 0; // we'll keep the loop number as a separate counter
switch (operation) {
case INCREMENT:
for (int i = startNumber; i < endNumber; i = i + updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i);
}
break;
case DECREMENT:
for (int i = startNumber; i > endNumber; i = i - updateNumber) {
loopNumber++;
performAssignmentPrinting(loopNumber, i)
}
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
}
private static void performAssignmentPrinting(int loopNumber, int value) {
System.out.println("loop#" + loopNumber + "\tvalue=" + value);
}
}
or the do/while version:
// now do the "meat" of the assignment
int currentNumber = startNumber;
int loopNumber = 0; // we'll keep the loop number as a separate counter
do {
loopNumber++;
switch (operation) {
case INCREMENT:
currentNumber += updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case DECREMENT:
currentNumber -= updateNumber;
performAssignmentPrinting(loopNumber, currentNumber);
break;
case INVALID:
default:
throw new IllegalStateException("Please enter supported operation! (increment/decrement)");
}
} while (currentNumber != endNumber);
you have i = i-3; out of loop.
Move decrementation of i into loop:
do {
System.out.println("loop#" + j + "\tvalue=" + i);
j++;
i = i - 3;
} while (i > endnumber);
For loop is the solution for your program. for(a ; b ; c) {...}
Google how a for loop works. And try to understand how the 3 parts a,b,c works.
Pseudo:
// if decrease mode
// for (i = upperbound ; i >= lowerbound ; i-= decrement)
// print i
// if increase mode
// for (i = lowerbound ; i <= upperbound ; i+= increment)
// print i
Update: This is sufficient to get you started and add more validation on your journey.

How do I get the numberOfQuestions variable to reset back to Zero after the loop completes?

/*Class MentalMathProgram
Michael
11/18/2020
This program is designed to present the user with randomly generated numbers
and it gets progressively harder for every question correct.
/
import java.util.;
public class mentalMathProgram {
static double ranNum(int min, int max){
Random ran = new Random();
double ranNum = min + (int)(Math.random() * ((max- - min)+ 1));
return (double)ranNum;
}
static byte mathType(int min, int max){
Random ran = new Random();
int mathType = min + (int)(Math.random() * ((max- - min)+ 1));
return (byte) mathType;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int restart = 0;
int correctAnswers = 0,incorrectAnswers = 0;
int numberOfQuestions = 0;
byte mathType = 0;
char again;
again = 'Y';
while(again == 'Y') {
do{
int questionCounter = 0;
System.out.println(" \n\nWelcome to your mental math assistance program! There will"
+ "\n be varying levels of difficulty as you progress through the questions"
+ "\n or when you select the difficulty preset. "
+ "\n\n Please select a difficulty below!");
System.out.println("\n 1. Easy"
+ "\n 2. Normal"
+ "\n 3. Medium"
+ "\n 4. Hard");
byte difficultyChoice = input.nextByte();
switch(difficultyChoice){
case 1: {
System.out.println("How many Questions do you want to do?");
numberOfQuestions = input.nextInt();
do {
byte randomOperationMin = 1;
byte randomOperationMax = 4;
byte operationValue = mathType(randomOperationMin,randomOperationMax);
mathType = operationValue;
switch(mathType) {
case 1: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "+" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 + result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 2: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "-" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 - result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 3: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
int result1=(int) ranNum(easyMin,easyMax);
int result2=(int) ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "*" +result2+ "=");
int userAnswer = input.nextInt();
int answer = result1 * result2;
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
case 4: {
System.out.println("\n\n\n Easy difficulty Selected");
int easyMin = 1;
int easyMax = 10;
double result1=ranNum(easyMin,easyMax);
double result2=ranNum(easyMin,easyMax);
System.out.println("What is "+result1+ "/" +result2+ "=");
double userAnswer = input.nextDouble();
double answer = result1 / result2;
double remainder = result1 % result2;
System.out.println("The Remainder is "+remainder);
if(userAnswer==answer) {
System.out.println("Correct!");
correctAnswers++;
}
else {
System.out.println("Incorrect! The Answer was "+answer);
incorrectAnswers++;
}
questionCounter = correctAnswers + incorrectAnswers;
break;
}
}
}while(questionCounter != numberOfQuestions);
break;
//I need to figure out a way to loop this code over and over instead of it just breaking out. I also need to
// make it so that the user can exit the program whenever they want
}
}
}while(restart==0);//condition for the do while death/restart loop
System.out.println("\nPlay Again? Y OR N: ");
//println statement, asking if user would like to play again.
System.out.println("Questions Correct: "+correctAnswers+"");
again = input.nextLine().charAt(0);
// set variable again to value assigned from user input
}
}
}
This is my code but I'm very new to coding. Im just trying to reset the variable that controls the amount of questions presented to the user to reset at the end of each loop. So far I'm unable to figure out what I'm doing wrong
There are a number of issues with your code that makes it difficult to trace / debug.
If I understand correctly, your outer doWhile is supposed to run indefinitely until user chooses to terminate the program.
The second doWhile is controlling the number of questions that are being asked in any single, complete round of the game.
Firstly, bring the 'numberOfQuestions' variable to be within the scope of the outer loop.
Secondly, you can simply declare a boolean variable to control whether the user wants to continue playing the game or to terminate the program.
Lastly, for each of the switch cases, you can simply do questionCounter++, instead of summing the correct and incorrect answers.
boolean keepGoing = true;
do {
int numberOfQuestions = 0;
int questionCounter = 0;
System.out.println("How many questions?");
numberOfQuestions = sc.nextInt();
do {
// ask questions repeatedly
// for each case, questionCounter++
} while (questionCounter != numberOfQuestions);
System.out.println("Enter '0' to continue");
if (input.nextInt() != 0) {
keepGoing = false;
}
} while (keepGoing);
It is also good practice to make sure your lines are indented properly, so that you are able to see what codes belong in which block for better maintainability and debugging.

Java Slot Machine Slot Comparison Trouble

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.

update a variable in a different class

How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.

Final touches on my Java code?

I'm more than 90 percent done with my code... Wanna add a few things but I've got no idea how to proceed.
This is my code so far... I have other classes as well, and I'm calling them in this code.
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SensorStatsApp extends Sensor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
HumiditySensor hSensor = new HumiditySensor();
int sChoice = -2;
int hChoice = -2;
int seasonTemp = -2;
int humidityTemp = -2;
int iterations = -2;
while(true)
{
try {
System.out.println("What season would you like to simulate?");
System.out.println(" 1. Winter \n 2. Spring \n 3. Summer \n 4. Fall \n 5. Random \n 6. EXIT");
System.out.print("Selection: ");
sChoice = sc.nextInt(); // gathers user input for which season to simulate
System.out.println(); // adds a break from the previous question
if(sChoice == 6){
System.exit(0); // exits the program
}
System.out.println("What humidity would you like to simulate?");
System.out.println(" 1. Full Range \n 2. Low Humidity \n 3. High Humidity \n 4. Random \n 5. EXIT");
System.out.print("Selection: ");
hChoice = sc.nextInt(); // gathers user input for humidity to simulate
System.out.println(); // adds a break from previous question
if(hChoice == 5){
System.exit(0); // exits the program
}
System.out.print("Input number of simulations: ");
iterations = sc.nextInt(); // gathers user input for number of iterations
}
catch(InputMismatchException e) { // if user inputed non numeric characters
System.out.println(e + " - Error: expecting a number for input");
return; // exits the program
}
for(int i = 0; i < iterations; i++){
try {
seasonTemp = seasonToSimulate(sChoice); // sends the sChoice int to be converted
humidityTemp = humidityToSimulate(hChoice); // sends the sChoice int to be converted and processed
display(seasonTemp, humidityTemp, i); // displays the current iteration of information
}
catch(IOException e){
System.out.println(e + " - Error: user input"); // lets the user know why their sChoice failed.
return; // doesn't return anything cause the return type is void. This just ends the program.
}
}
}
}
public static void display(int sTemp, int hTemp, int iteration){
System.out.println();
System.out.println(++iteration + " Simulations:");
System.out.println("Season Temperature: " + sTemp);
System.out.println("Humidity Temperature: " + hTemp);
System.out.println();
}
public static int humidityToSimulate(int choice) throws IOException {
int temp = -2;
HumiditySensor hSensor = new HumiditySensor();
Boolean done = false; // if random another iteration through switch is needed
while(!done){ // if the user decides to use random then done != true so I can iterate one more time in the switch statement
switch(choice){ // sChoice is the season in terms of an int
case 1: { // full range, if choice is 1 it falls into this case and breaks at the statement break; (ends the current switch)
temp = hSensor.getHumidity();
done = true;
break;
}
case 2: { // low humidity, if choice is 2 it falls into this case.
temp = hSensor.getLowHumidity();
done = true;
break;
}
case 3: { // high humidity
temp = hSensor.getHighHumidity();
done = true;
break;
}
case 4: { // random
choice = (int) Math.random() * 3; // random times (3) for 3 humidity types
if(choice == 0) choice++; // 0 is a possibility but not an option
break;
}
case 5: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
public static int seasonToSimulate(int choice) throws IOException {
int temp = -1;
TemperatureSensor tSensor = new TemperatureSensor();
Boolean done = false; // if random through switch is needed
while(!done){
switch(choice) {
case 1: { // winter
temp = tSensor.getWinterTemp();
done = true;
break;
}
case 2: { // spring
temp = tSensor.getSpringTemp();
done = true;
break;
}
case 3: { // summer
temp = tSensor.getSummerTemp();
done = true;
break;
}
case 4: { // fall
temp = tSensor.getFallTemp();
done = true;
break;
}
case 5: { // random
choice = (int) Math.random() * 4;// random *(4) for 4seasons
if(choice == 0) choice++;// 0 is a possibility not an option
break;
}
case 6: { // exit
temp = -1; // lets the calling function know it's done
break;
}
default:
{
throw new IOException(); // user gave improper option
}
}
}
return temp;
}
}
How would I do the following in my program?
Each iteration should display the readings being generated for each temperature and humidity. At the end your program should display a summary of the simulation as follows:
Season: _________ (if random, then display Random:Summer for example)
1- First temperature generated
2- Last temperature generated
3- Lowest temperature generated
4- Highest temperature generated
5- Total sum of all temperatures generated
6- Average for the season
Humidity Type: _________ (if random, then display Random:Full for example)
1- First humidity reading generated
2- Last humidity reading generated
3- Lowest humidity reading generated
4- Highest humidity reading generated
5- Total sum of all humidity readings generated
6- Average humidity reading

Categories