Math Logic in Java for Lemonade Stand Game - java

I am writing the lemonade stand game in Java but I am having a bit of trouble trying to figure out the perfect recipe. I mean something like if weather is Sunny and temperature is greater than 85 the perfect recipe would be 8 lemons, 6 cups of sugar and 12 ice cubes per cup. I have most of the code done, except the math logic seems a little off. Please let me know how can I improve the code. I included all the code so you can get a better idea on how all the logic goes so far.
public static void main(String[] args) {
///declaration of variables
int playAgain;
int days, customers = 120;
int CUPS_PITCHER = 14;
double money = 20.00, earned = 0;
double [] cupsPrice = {0.93, 1.65, 2.77}, lemonsPrice = {0.98, 2.05, 4.38}, sugarPrice = {0.74, 1.63, 3.31}, icePrice = {0.99, 2.01, 3.95};
//inventory
///string input
String cupsS = "", lemonsS = "", sugarS = "", iceS = "";
//int input values
int cups = 0, lemons = 0, sugar = 0, ice = 0;
//String for Pitcher
double priceCup;
int lemonsPitcher, sugarPitcher, iceCup;
////array for items options
String [] cupsOptions = {"25","50","100"};
String [] lemonsOptions = {"10","30","75"};
String [] sugarOptions = {"8","20","48"};
String [] iceOptions = {"100","250","500"};
int temperature;
String [] weather = {"Sunny","Hazy","Cloudy","Overcast","Rainny"};
JOptionPane.showMessageDialog(null,"Welcome to our Lemonade Stand Game");
days = getDays();
///set flag for loops
boolean ingredients, cupsFlag, lemonsFlag, sugarFlag, iceFlag;
boolean [] flag = {false,false,false,false};
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
String [] itemName = {"Cups","Lemons","Sugar","Ice Cubes"};
String [][] itemOptions = {cupsOptions,lemonsOptions,sugarOptions,iceOptions};
for(int i=1; i<=days; i++){
/////random weather
Random rand = new Random();
int randomWeather = rand.nextInt(5);
//random temperature from 59 to 99
temperature = rand.nextInt(99-59) + 59;
int response = 0;
///loop while not play game
while(response != 1){
String[] options = new String[] {"Buy", "Play Game", "Cancel"};
response = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + "\nCups: " + cups + " *** Lemons: " + lemons + "\nSugar: " +
sugar + " *** Ice: "+ice + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
ingredients = false;
///if buy ingredientes ** when they click buy
while(response == 0 && !ingredients){
String[] optionsBuy = new String[] {"Buy Cups", "Buy Lemons", "Buy Sugar", "Buy Ice","Back to Game"};
String line1 = "\n25 Cups: $" + cupsPrice[0] + " 10 Lemons: $" + lemonsPrice[0]
+ " 8 Cups of Sugar: $" + sugarPrice[0] + " 100 Ice Cubes: $"+icePrice[0];
String line2 = "\n50 Cups: $" + cupsPrice[1] + " 30 Lemons: $" + lemonsPrice[0]
+ " 20 Cups of Sugar: $" + sugarPrice[1] + " 250 Ice Cubes: $"+icePrice[1];
String line3 = "\n100 Cups: $" + cupsPrice[2] + " 75 Lemons: $" + lemonsPrice[2]
+ " 48 Cups of Sugar: $" + sugarPrice[2] + " 500 Ice Cubes: $"+icePrice[2];
int responsePurchase = JOptionPane.showOptionDialog(null, "You currently have " + defaultFormat.format(money) + " Day " + i + line1 + line2 + line3 + "\nHigh Temperature: " + temperature + "\nWeather Forecast: " + weather[randomWeather], "Inventory",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, optionsBuy, optionsBuy[0]);
double [][] priceOptions = {cupsPrice,lemonsPrice,sugarPrice,icePrice};
int [] qty = {0,0,0,0};
for(int j=0; j<4; j++){
if(responsePurchase == j)
qty[j] = buyItems(itemName[j],itemOptions[j],flag[j],money);
//money = money - itemPrice[j][0];
}
///deduct money
for(int k=0;k<4;k++){
for(int j=0;j<3;j++){
if(qty[k] == Integer.parseInt(itemOptions[k][j])){
money = money - priceOptions[k][j];
}
}
}
////add items purchased
cups += qty[0];
lemons += qty[1];
sugar += qty[2];
ice += qty[3];
//System.out.println(itemOptions[0][1]);
/*
if(qty[0] == 25){
money = money - cupsPrice[0];
}
if(qty[0] == 50){
money = money - cupsPrice[1];
}
if(qty[0] == 100){
money = money - cupsPrice[2];
}
// buy lemons
cupsFlag = false;
if (responsePurchase == 0) {
int qty = buyItems("Cups",cupsOptions,cupsFlag,money);
if (qty != 0) {
cups += qty;
}
}
// buy lemons
lemonsFlag = false;
if (responsePurchase == 1) {
int qty = buyItems("Lemons",lemonsOptions,lemonsFlag,money);
if (qty != 0) {
lemons += qty;
}
}
*/
///go back to game when back to game click
if(responsePurchase == 4){
ingredients = true;
}
}///end while buy ingredients
}///end while buy
JTextField fieldCup = new JTextField("0.25");
JTextField fieldLemons = new JTextField("4");
JTextField fieldSugar = new JTextField("4");
JTextField fieldIce = new JTextField("4");
Object[] fields = {"Price per Cup in Cents", fieldCup,"Lemons per Pitcher", fieldLemons,"Sugar per Pitcher", fieldSugar, "Ice per Cup", fieldIce};
int responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
while(!validateDouble(fieldCup.getText()) || !validateInt(fieldLemons.getText()) || !validateInt(fieldSugar.getText()) || !validateInt(fieldIce.getText())){
if(responsePitcher == JOptionPane.CANCEL_OPTION){
int stopGame = JOptionPane.showConfirmDialog(null,"Do you wish to cancel the game? All progress will be lost","",JOptionPane.YES_NO_OPTION);
if(stopGame == JOptionPane.YES_OPTION){
System.exit(0);
}
}
JOptionPane.showMessageDialog(null,"One of the inputs is incorrect! try Again","ERROR",JOptionPane.ERROR_MESSAGE);
responsePitcher = JOptionPane.showConfirmDialog(null,fields,"Price",JOptionPane.OK_CANCEL_OPTION);
}
priceCup = Double.parseDouble(fieldCup.getText());
lemonsPitcher = Integer.parseInt(fieldLemons.getText());
sugarPitcher = Integer.parseInt(fieldSugar.getText());
iceCup = Integer.parseInt(fieldIce.getText());
for(int k=0; k<5; k++){
if(weather[randomWeather].equals(weather[k])){
////if weather is not sunny reduce possible customers
if(!weather[randomWeather].equals(weather[0])){
customers = customers - (customers * k/15);
}
}
}
//System.out.println(customers);///testing results
//System.out.println(fieldCup.getText());///testing results
System.out.println(customers);///testing results
//showBar();
///perfect recepie
if(temperature > 58){
///if sunny
if(weather[randomWeather].equals(weather[0])){
}
}
//too expensive or not right ingredients reduce possible customers
if(priceCup > 0.25){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(lemonsPitcher > 7 || lemonsPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(sugarPitcher > 7 || sugarPitcher < 5){
customers = customers - (customers * 10/100);///reduce customers by 10%
}
if(iceCup > 10 || iceCup < 6){
customers = customers - (customers * 15/100);///reduce customers by 15%
}
///determine max cups according to inventory
int maxCupsLemons = (lemons / lemonsPitcher) * CUPS_PITCHER;
int maxCupsSugar = (sugar / sugarPitcher) * CUPS_PITCHER;
int maxCupsIce = (ice / iceCup);
int maxCupsp = cups;
int [] maxCups = {maxCupsLemons, maxCupsSugar, maxCupsIce, maxCupsp};
System.out.println(Arrays.toString(maxCups));
int minValue = maxCups[0];
for(int m=0;m<maxCups.length;m++){
if(maxCups[m] < minValue){
minValue = maxCups[m];
}
}
System.out.println(minValue);
if(minValue < customers){
customers = minValue;
}
System.out.println(customers);///testing results
////profit
earned = priceCup * customers;
money += earned;
///deduct inventory
//14 cups per pitcher
int lemonsSpent = (customers / CUPS_PITCHER) * lemonsPitcher;
int sugarSpent = (customers / CUPS_PITCHER) * sugarPitcher;
lemons = lemons - lemonsSpent;
sugar = sugar - sugarSpent;
cups = cups - customers;
JOptionPane.showMessageDialog(null,"Your profit for day " + i + " is " + defaultFormat.format(earned));
/////reset variables for next day
customers = 120;
earned = 0;
ice = 0;
}
//JOptionPane.showMessageDialog(null,days);
}
}

I think your problem is on the pricing.
Better leave it as 14 cups. Then generate the price per cup.
First, you should have a standard measure on how many cups of an ingredient will be in one pitcher. That way, you will have a basis.
Let's say. 8 lemons + 6 cups of sugar + 12 ice cubes = 1 pitcher
Multiply the cup price. 8 * 0.98, etc. then add it to other ingredients price.
But, it will be better and easier if you will remove the pitcher from the price computation. Since you will sell it by cups.
I'll give you a tip in formulating a program's logic. Most of the time, the obvious way to do it is the easiest way. Put yourself in the position of the program, if you were the program, what will you do?
In improving your program's logic, check every thing your program does. Ask yourself, is it the most likely thing I will do?
If your program works, never fear to take risks. Try other ways, try other algorithms, and read. Then decide which of those will improve your work. Most of the time trying something new begets failure, but that's the bittersweet way of learning.
Happy coding!

Related

Declaring String Variables within a while loop without it looping all throughout - java

I am stuck at a part where I am supposed to declare a string variable called "phrase", where it shouldn't loop, all the way through.
to give you an idea my task is: Similar to Option 1 except the user enters 'N' (instead of 'Q') when they are done entering results for the first team. Then, the program inputs a second team name and its results until 'Q' is entered. Outputs two statements, like the statements in option 1 followed by a third statement that says which team is in first place (based on the number of points)
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal // how would I make this appear in the same while loop?
L
L
O
L
L
W
L
L
Q
Sample output:
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
UPDATE:
My code:
else if (option == 2){
int counter = 0;
int totalpoints = 0;
String phrase = keyboard.next();
while(go){
String letter = keyboard.next();
if (letter.equals("W")){
pointsW++;
}
else if (letter.equals("L")){
pointsL++;
}
else if (letter.equals("O")){
pointsO++;
}
counter++;
if (letter.equals("N")){
totalpoints = pointsW + pointsL + pointsO;
counter--;
go = false;
}
}
int counter2 = 0;
int totalpoints2 = 0;
pointsW = 2;
pointsL = 0;
pointsO = 1;
String phrase2 = keyboard.next();
while (go2){
String letter2 = keyboard.next();
if (letter2.equals("W")){
pointsW++;
}
else if (letter2.equals("L")){
pointsL++;
}
else if (letter2.equals("O")){
pointsO++;
}
counter2++;
if (letter2.equals("Q")){
counter2--;
totalpoints2 = pointsW + pointsL + pointsO;
go2 = false;
}
}
System.out.println(phrase + " has played "+counter+" games and has earned "+totalpoints+" points");
System.out.println(phrase2 + " has played "+counter2+" games and has earned "+totalpoints2+" points");
if (totalpoints > totalpoints2){
System.out.println(phrase + " is in first place by "+(totalpoints - totalpoints2) + " points");
}else{
System.out.println(phrase2 + " is in first place by "+(totalpoints2 - totalpoints) + " points");
}
}
Sample input:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
The issue: This is the output I am getting "Montreal played 8 games and has earned 11 points" where instead it should be "Montreal has played 8 games and has earned 3 points"
The output I am getting
You can reuse the same variables for individual points i.e. pointsW and pointsO because you do not want to retain their values till the end where you are publishing the results. The same is the case with the variable for the loop condition i.e. go and the variable used for inputting win/loss i.e. letter.
You will need arrays or different variables for storing total points, countings, and team name.
import java.util.Scanner;
public class Standings {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int option = keyboard.nextInt();
int pointsW = 0;
int pointsO = 0;
String letter;
boolean go = true;
if (option == 2) {
// Variables for total points, counting, and name for the first team
int playedGamesTeamOne = 0;
int teamOnePoints = 0;
String teamOneName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamOne++;
if (letter.equals("N")) {
teamOnePoints = pointsW + pointsO;
playedGamesTeamOne--;
go = false;
}
}
// Reset common variables
go = true;
pointsW = 0;
pointsO = 0;
// Variables for total points, counting, and name for the second team
int playedGamesTeamTwo = 0;
int teamTwoPoints = 0;
String teamTwoName = keyboard.next();
while (go) {
letter = keyboard.next();
if (letter.equals("W")) {
pointsW += 2;
} else if (letter.equals("O")) {
pointsO++;
}
playedGamesTeamTwo++;
if (letter.equals("Q")) {
teamTwoPoints = pointsW + pointsO;
playedGamesTeamTwo--;
go = false;
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned "
+ teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned "
+ teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out
.println(teamOneName + " is in first place by " + (teamOnePoints - teamTwoPoints) + " points");
} else {
System.out
.println(teamTwoName + " is in first place by " + (teamTwoPoints - teamOnePoints) + " points");
}
}
}
}
A sample run:
2
Toronto
W
W
L
O
W
O
W
N
Montreal
L
L
O
L
L
W
L
L
Q
Toronto has played 7 games and has earned 10 points
Montreal has played 8 games and has earned 3 points
Toronto is in first place by 7 points
you can use this code for option two
Scanner keyboard = new Scanner(System.in);
int teamCounter = 1;
//String[] teamsNames = new String[2];
String teamOneName="";
String teamTwoName="";
//int[] playedGames = new int[2];
int playedGamesTeamOne = 0;
int playedGamesTeamTwo = 0;
//int[] points = new int[2];
int teamOnePoints = 0;
int teamTwoPoints = 0;
boolean firstTimeTeam1 = true;
boolean firstTimeTeam2 = true;
while (teamCounter <= 2) {
if (teamCounter == 1) {
if (firstTimeTeam1) {
teamOneName = keyboard.nextLine();
firstTimeTeam1 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamOnePoints += 2;
playedGamesTeamOne++;
} else if (letter.equals("L")) {
playedGamesTeamOne++;
} else if (letter.equals("O")) {
teamOnePoints += 1;
playedGamesTeamOne++;
} else if (letter.equals("N")) {
teamCounter++;
}
} else {
if (firstTimeTeam2) {
teamTwoName = keyboard.next();
firstTimeTeam2 = false;
}
String letter = keyboard.next();
if (letter.equals("W")) {
teamTwoPoints += 2;
playedGamesTeamTwo++;
} else if (letter.equals("L")) {
playedGamesTeamTwo++;
} else if (letter.equals("O")) {
teamTwoPoints += 1;
playedGamesTeamTwo++;
} else if (letter.equals("Q")) {
teamCounter++;
}
}
}
System.out.println(teamOneName + " has played " + playedGamesTeamOne + " games and has earned " + teamOnePoints + " points");
System.out.println(teamTwoName + " has played " + playedGamesTeamTwo + " games and has earned " + teamTwoPoints + " points");
if (teamOnePoints > teamTwoPoints) {
System.out.println(teamOneName + " is in first place by " + (teamOnePoints-teamTwoPoints) + " points");
} else {
System.out.println(teamTwoName + " is in first place by " + (teamTwoPoints-teamOnePoints) + " points");
}

Why isn't my live result updating in main?

I'm making a currency tracker to track the live value of bitcoin.
the class "bitcoinlive" runs Correctly if I run it in its own main method, but it won't work when I make an instance of the file. I need it to print the live value you of bitcoin.
I try to print out the variable "a53" but I don't know if I'm doing it right.
Here are the list of imports for the bitcoinlive class because it kept giving me an error message and wouldn't allow this to be apart of the code when posting this.
public static void main(String[] args) {
Dates d = new Dates();
String s = d.getDate();
System.out.println("Date is" + s);
W3 mywallet = new W3();
Bitcoinlive mybitcoinlive = new Bitcoinlive();
L3 myledger = new L3();
Scanner myscanner = new Scanner(System.in);
double buy = 0.0;
int choice = 0;
double bitcoin = 4000;
double USD = 20000;
while (choice != 5) {
System.out.println("Welcome! Enter a command. \n"
+ "Enter 1) Buy Bitcoin \n"
+ "Enter 2) Sell Bitcoin \n"
+ "Enter 3) Print Balance \n"
+ "Enter 4) Print History \n"
+ "ENTER 5) Exit Program\n");
choice = myscanner.nextInt();
if (choice == 1) {
System.out.println("How many? ");
buy = myscanner.nextDouble();
mywallet.add(buy);
bitcoin = bitcoin * buy;
USD = USD - bitcoin;
myledger.save(s);
System.out.println("you have bought:" + mywallet.numcoins);
System.out.println(USD);
System.out.println(mybitcoinlive.a53);
bitcoin = 4000;
} else if (choice == 2 && USD >= bitcoin) {
System.out.println("How many?");
buy = myscanner.nextDouble();
mywallet.subtract(buy);
System.out.println("you have sold:" + mywallet.numcoins);
USD = USD + bitcoin;
System.out.println(USD);
bitcoin = 4000;
myledger.save(s);
} else if (choice == 3) {
System.out.println("Balance:" + mywallet.numcoins);
} else if (choice == 4) {
System.out.println("Transaction history: ");
System.out.println("you have made" + myledger.getsize() + "transactions"
+ d.getDate());
} else if (choice == 5) {
// exit
break;
} else if (choice == 7) {
System.out.println(mybitcoinlive.price);
}
}
System.out.println("Bye");
}
this is my separate class
public class Bitcoinlive {
Double a53=0.0;
double price;
Double get() {
try {
String urlcoincapeth13 = "https://api.coinmarketcap.com/v1/ticker/bitcoin/";
Document docblocktradescoincapeth13 = Jsoup.parse(new URL(urlcoincapeth13).openStream(), "UTF-8", "", Parser.xmlParser());
String a13 = docblocktradescoincapeth13.toString();
int a23 = a13.indexOf("price_usd") + 13;
int a33 = a13.indexOf("price_btc") - 4;
String a43 = a13.substring(a23, a33);
a53 = Double.parseDouble(a43);
} catch (Exception e) {
System.out.println("Error accessing bitcoin values");
}
return a53;
}
}
Your class Bitcoinlive stores the price in a field called a53. You can update this field by calling get(). However, it looks like you're never calling get() - you're just calling the field:
System.out.println(mybitcoinlive.a53);
Try replacing that line with:
System.out.println(mybitcoinlive.get());
Or refresh it first:
mybitcoinlive.get();
System.out.println(mybitcoinlive.a53);

Trying to keep new ending balance if while loop repeats

I have to create a game that prompts the user to put in a starting balance and then place a bet. Then they win or lose and their balance is added or subtracted accordingly. My problem is that I don't know how to make the program remember the final balance before starting over in the while loop if the player wants to play again. My balance stays as the original first balance entered when the user is prompted. I'm sorry if this is a repeat, but I couldn't find a question like this and I've been searching for over an hour. Thanks in advance.
import static java.lang.Math.*;
import java.util.Scanner;
public class BetGame
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
int die1, die2;
boolean looping = true;
System.out.println("Please enter your starting balance in whole dollars:");
double balance = in.nextDouble();
System.out.println("Your beginning balance is " + balance + ", good luck!!");
int guess = 0;
double bet2 = 0;
double endingBalance = 0;
while(looping) {
while (guess < 3) {//to allow the user to do this only 3 times
System.out.println("Enter a valid bet:");
double bet = in.nextDouble();
if (bet >= balance || bet >= endingBalance){
System.out.println("That is more than your balance.");
}
else if (bet < balance || bet < endingBalance) {
bet2 = 0 + bet;
break;
}
guess++;
if (guess == 3) {
looping = false;
System.out.println("You have entered three invalid bets in a row. Please leave the casino.");
}
}
die1 = RollDie();
die2 = RollDie();
int sum = die1 + die2;
if (2 <= sum && sum <= 6) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a win!");
endingBalance = balance + bet2;
}
else if (7 <= sum && sum <= 12) {
System.out.println("The roll is " + die1 + " and " + die2 + " for a " + sum + " for a lose!");
endingBalance = balance - bet2;
}
System.out.println("Your balance is " + endingBalance);
System.out.println("Do you want to roll again?");
String answer = in.next();
if ((answer.equals("n")) || (answer.equals("N"))) {
looping = false;
}
}
System.out.println("Your balance is " + endingBalance + ". Better luck next time! Have a wonderful evening!");
}
static int RollDie()
{
int min = 1;
int max = 6;
return myRandomInteger(min, max);
}
static int myRandomInteger(int min, int max)
{
double range = max - min + 1.0;
int randomNum = (int)(range * Math.random()) + min;
return randomNum;
}
}
You can store the balance in a variable
double balance = in.nextDouble();
double originalBalance = balance;

Array Method with If statement in Java

I am a graduate student learning the Java program. As a homework assignment, we are to do the following:
Create a menu of items where the user can input choices into an array
Create a method that figures out the prices of the items chose and return the sum
Right now, my output shows that the total being returned from the method is actually adding all the prices in the if statement instead of coordinating them with the user input array that was copied (see example output on bottom). We have not touched upon anything further than the standard array (no ArrayList or other methods). Please offer any advice, I will do my best to figure it out.
import java.util.Arrays;
import java.util.Scanner;
public class Online_Purchasing_HW6 {
public static final int ARRAY_LENGTH = 10; //Length of the array
public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Reads user input
int[] naMenuChoice = new int [ARRAY_LENGTH]; //Array for items chosen
String[] naMenu = new String [ARRAY_LENGTH]; //Array for menu items
int[] naItemPrice = new int [9]; //Array for item prices
String sCustomerName; //String for customer's name
int nChoice = 0; //Option chosen in menu by user/Used as Index
int nSum = 0; //Sum of items chosen
double dTotalPrice = 0; //Total price plus taxes
double dTaxes = 0; //Total taxes to be applied to total
//Declare Constants
final int SENTINEL = 10; //Used to end loop
final double SALES_TAX = 0.065; //Sales tax to be used
//Choices for menu denoted by strings
String sChoice1 = "1. Smartphone" + "\t" + "\t" + "$249";
String sChoice2 = "2. Smartphone Case" + "\t" + "$39";
String sChoice3 = "3. PC Laptop" + "\t" + "\t" + "$1149";
String sChoice4 = "4. Tablet" + "\t" + "\t" + "$349";
String sChoice5 = "5. Tablet Case" + "\t" + "\t" + "$49";
String sChoice6 = "6. eReader" + "\t" + "\t" + "$119";
String sChoice7 = "7. PC Desktop" + "\t" + "\t" + "$899";
String sChoice8 = "8. LCD Monitor" + "\t" + "\t" + "$299";
String sChoice9 = "9. Laser Printer" + "\t" + "$399";
String sChoice10 = "10. Complete my order";
//Prompt user for name
System.out.print("Please enter your name: ");
//Read customer's name
sCustomerName = input.nextLine();
//Menu of items for purchase
System.out.print("\n");
System.out.println("Best Purchase Products");
System.out.println(sChoice1);
System.out.println(sChoice2);
System.out.println(sChoice3);
System.out.println(sChoice4);
System.out.println(sChoice5);
System.out.println(sChoice6);
System.out.println(sChoice7);
System.out.println(sChoice8);
System.out.println(sChoice9);
System.out.println(sChoice10);
//Prompt user for item selection
System.out.print("Please select an item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
//Loop to read integers from user
while (naMenuChoice[nChoice] != SENTINEL) {
//adds 1 everytime more than one item is chosen by the user
nChoice++;
//Prompt user for another choice since he/she has not chosen option "10"
System.out.print("Please select another item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();
} //end of while loop
System.out.print(Arrays.toString(naMenuChoice));
//If option 10 if chosen, the loop will end with this message
System.out.println("\n" + "Thank you for ordering with Best Purchase, " + sCustomerName );
//call calculateTotalPrice method passing Array
nSum = nCalculatePrice(naMenuChoice);
//Formulas
//Sales Tax
dTaxes = SALES_TAX * nSum;
//Total Amount Due
dTotalPrice = dTaxes + nSum;
System.out.println("Total items ordered: " + nChoice);
System.out.println("Price of items ordered: $" + nSum);
System.out.println("Sales tax: $" + dTaxes);
System.out.println("Total amount due: $" + dTotalPrice);
}//end of main method
//Method for calculating price
public static int nCalculatePrice(int[] naChoicesToPrice){
int nTotalPrice = 0; //int value to return
int nIndex = 0; //used as counter
int nItemPrice = 0; //used to assign price of items
int[] naAddedPrices = new int[ARRAY_LENGTH]; //new array for assigning prices
//For loop to sum up all entries from naItemPrice array
for (nIndex = 0; nIndex < ARRAY_LENGTH; nIndex++){
naAddedPrices[nIndex] = naChoicesToPrice[nIndex];
//end of For Loop
if (nIndex == 1) {
nItemPrice = 249;
nTotalPrice += nItemPrice;}
if (nIndex == 2) {
nItemPrice = 39;
nTotalPrice += nItemPrice;}
if (nIndex == 3) {
nItemPrice = 1149;
nTotalPrice += nItemPrice;}
if (nIndex == 4) {
nItemPrice = 349;
nTotalPrice += nItemPrice;}
if (nIndex == 5) {
nItemPrice = 49;
nTotalPrice += nItemPrice;}
if (nIndex == 6) {
nItemPrice = 119;
nTotalPrice += nItemPrice;}
if (nIndex == 7) {
nItemPrice = 899;
nTotalPrice += nItemPrice;}
if (nIndex == 8) {
nItemPrice = 299;
nTotalPrice += nItemPrice;}
if (nIndex == 9) {
nItemPrice = 399;
nTotalPrice += nItemPrice;}
} //end of for loop
return nTotalPrice;
}//end of naCalculatePrice method
}//end of class
Corresponding output for the program is:
Please enter your name: John Smith
Best Purchase Products
1. Smartphone $249
2. Smartphone Case $39
3. PC Laptop $1149
4. Tablet $349
5. Tablet Case $49
6. eReader $119
7. PC Desktop $899
8. LCD Monitor $299
9. Laser Printer $399
10. Complete my order
Please select an item from the menu above: 9
Please select another item from the menu above: 10
[9, 10, 0, 0, 0, 0, 0, 0, 0, 0]
Thank you for ordering with Best Purchase, John Smith
Total items ordered: 1
Price of items ordered: $3551
Sales tax: $230.815
Total amount due: $3781.815
As you can see, I chose only one item from the menu but it adds up all the prices. I've been on this assignment for 2 weeks so far and I'm growing desperate. I've read most articles on this site pertaining to this subject, read many articles on just methods and arrays, respectively and still can't formulate a working program.Any help would be appreciated.
Nice work so far.
In your for loop to sum up, you have to look into naMenuChoices to see what the customer has ordered. Remember, you may find a 0 or a 10 there, in which case you should not add anything to the sum. Good luck, you’re not that far from your goal.
You may want to make yourself a class for the product/items like
public class Product {
private String itemText;
private int itemPrice;
public Product(String itemText, int itemPrice) {
this.itemText = itemText;
this.itemPrice = itemPrice;
}
public int getItemPrice() {
return itemPrice;
}
#Override
public String toString() {
return itemText + "\t\t$" + itemPrice;
}
}
Fill 9 objects of this class into an array, use them for building the sChoice Strings and use it instead of the naItemPrice array. Modify my code to your needs. It should give a better overview of the code. And eliminate the risk of accidentally charging another price from the customer than the one announced.
for (int i = 0; i < ARRAY_LENGTH; i++){
if(naChoicesToPrice[i]==0 || naChoicesToPrice[i]==10){
nItemPrice = 0;
}
else{
if (naChoicesToPrice[i] == 1) {
nItemPrice = 249;
}
if (naChoicesToPrice[i] == 2) {
nItemPrice = 39;
}
if (naChoicesToPrice[i] == 3) {
nItemPrice = 1149;
}
if (naChoicesToPrice[i] == 4) {
nItemPrice = 349;
}
if (naChoicesToPrice[i] == 5) {
nItemPrice = 49;
}
if (naChoicesToPrice[i] == 6) {
nItemPrice = 119;
}
if (naChoicesToPrice[i] == 7) {
nItemPrice = 899;
}
if (naChoicesToPrice[i] == 8) {
nItemPrice = 299;
}
if (naChoicesToPrice[i] == 9) {
nItemPrice = 399;
}
}
nTotalPrice += nItemPrice;
} //end of for loop
return nTotalPrice;
}

Adding a counter to a java program with different methods

My program is a math game and will ask the user different questions in different levels. I would like to use a money rewards system that whenever they get one question right, $1000 will be added to their prize. I have tried to do this, however the money doesn't add when an answer is answered correctly. Help please on how I can go about fixing this.
import javax.swing.*;
import java.io.*;
public class mathGame
{
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed by the user
int money = 0;
String player = JOptionPane.showInputDialog(null, "Welcome to... \n - Are YOU Smarter Than a 12 Year Old? - \n Please enter your name to begin!", "Welcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hi " + player + ", " + " let's see if you are really smarter than a 12 year old. \n This games consists of 3 levels of difficulty. \n Answer all 4 questions in each level and earn $500, 000! \n If you get an answer wrong you lose $100, you go home EMPTY HANDED if your money reaches 0!");
Object[] options = {"Yes!", "No way!"};
int x = JOptionPane.showOptionDialog(null,"Are you ready to play?","Start?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (x == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "...Level: 1...");
JOptionPane.showMessageDialog(null, "Your first level consists of addition and substraction of 2 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int y = 0; y <= 3; y++){
addition();
subtraction();
}
JOptionPane.showMessageDialog(null, "...Level: 2...");
JOptionPane.showMessageDialog(null, "Your second level consists of addition and substraction of 3 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int z = 0; z <= 6; z++){
addSub();
}
}
else if (x == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
public static int addition()
{
int money = 0;
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
String sumA = JOptionPane.showInputDialog(null, firstNum + "+" + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int sum = Integer.parseInt (sumA);
int realSum = firstNum + secondNum;
if (sum == realSum){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (sum != realSum){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return sum;
}
public static int subtraction ()
{
int money =0;
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
if (firstNum < secondNum){
firstNum = secondNum;
secondNum = firstNum;
}
String differenceA = JOptionPane.showInputDialog(null, firstNum + " - " + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int difference = Integer.parseInt (differenceA);
int realDifference = firstNum - secondNum;
if (difference == realDifference){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (difference != realDifference){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return difference;
}
public static int addSub ()
{
int money = 0;
int signNum = (int)(Math.random()*1);
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
int thirdNum = (int)(Math.random()*10);
String answerA = JOptionPane.showInputDialog(null, firstNum + " + " + secondNum + " - " + thirdNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int answer = Integer.parseInt (answerA);
int realAnswer = firstNum + secondNum - thirdNum;
if (answer == realAnswer){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (answer != realAnswer){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return answer;
}
}
Don't do the math with local variables. Instead declare money as a instance variable:
public class mathGame
{
private static int money = 0;
(...)
Remove all the other int money = 0; from the code except the one above.
You have to declare you money variable as a class variable. If you see each time you call a method, you create a new variable money and set it to 0.
public class mathGame
{
static int money = 0;
Remove all the initializations of money (int money = 0;) in your method and it will works.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
public class mathGame
{
private static int money = 0;
public static void main (String [] args) throws IOException
{
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));// Buffered Reader reads the number inputed by the user
String player = JOptionPane.showInputDialog(null, "Welcome to... \n - Are YOU Smarter Than a 12 Year Old? - \n Please enter your name to begin!", "Welcome", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Hi " + player + ", " + " let's see if you are really smarter than a 12 year old. \n This games consists of 3 levels of difficulty. \n Answer all 4 questions in each level and earn $500, 000! \n If you get an answer wrong you lose $100, you go home EMPTY HANDED if your money reaches 0!");
Object[] options = {"Yes!", "No way!"};
int x = JOptionPane.showOptionDialog(null,"Are you ready to play?","Start?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (x == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "...Level: 1...");
JOptionPane.showMessageDialog(null, "Your first level consists of addition and substraction of 2 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int y = 0; y <= 3; y++){
addition();
subtraction();
}
JOptionPane.showMessageDialog(null, "...Level: 2...");
JOptionPane.showMessageDialog(null, "Your second level consists of addition and substraction of 3 numbers! \n In order to pass this level, you will need to answer all 6 questions correctly. \n For every correct question, you will earn $1,000.");
for (int z = 0; z <= 6; z++){
addSub();
}
}
else if (x == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null, "Goodbye!");
System.exit(0);
}
}
public static int addition()
{
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
String sumA = JOptionPane.showInputDialog(null, firstNum + "+" + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int sum = Integer.parseInt (sumA);
int realSum = firstNum + secondNum;
if (sum == realSum){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (sum != realSum){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return sum;
}
public static int subtraction ()
{
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
if (firstNum < secondNum){
firstNum = secondNum;
secondNum = firstNum;
}
String differenceA = JOptionPane.showInputDialog(null, firstNum + " - " + secondNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int difference = Integer.parseInt (differenceA);
int realDifference = firstNum - secondNum;
if (difference == realDifference){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (difference != realDifference){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return difference;
}
public static int addSub ()
{
int signNum = (int)(Math.random()*1);
int firstNum = (int)(Math.random()*20);
int secondNum = (int)(Math.random()*20);
int thirdNum = (int)(Math.random()*10);
String answerA = JOptionPane.showInputDialog(null, firstNum + " + " + secondNum + " - " + thirdNum + " = ", "Question", JOptionPane.INFORMATION_MESSAGE);
int answer = Integer.parseInt (answerA);
int realAnswer = firstNum + secondNum - thirdNum;
if (answer == realAnswer){
money = money + 1000;
JOptionPane.showMessageDialog(null, "CORRECT! \n You have $" + money);
}
else if (answer != realAnswer){
JOptionPane.showMessageDialog(null, "INCORRECT! \n You are not smarter than a 12 year old. \n You go home with $" + money);
System.exit(0);
}
return answer;
}
}
You need to make an instance variable. Also in each method you set the money = 0 so each time you called the method it turned to 0. Posted code works.
You are creating a new local money variable everytime you call a method so it will always start at 0 each call.
int money = 0;
You need to remove this statement at the start of addition, subtractionand addsub
The money variables you are using are local within each method (which means they are gone as soon as the methods exit). You need to get rid of all those money variables and declare one instance variable:
public class mathGame
{
/* Class variable, declared outside of any method */
static protected int money = 0;
...
/* Methods declaration here */
...
}
More info on Java variables.
It is probably a better idea, to not have all your methods and variables static and work with an Instance of the class instead.
Difference between Instance and Class variables.

Categories

Resources