How to use methods and call them within the Switch statement - java

I'm making a tax calculator for class but I can't quite figure out how to separate my code in my individual cases
println("Please enter your filing status: ");
println("Enter 0 for single filers,");
println(" 1 for married filing jointly,");
println(" 2 for married filing separately, or");
println(" 3 for head of household");
double tax = 0;
DecimalFormat df = new DecimalFormat("#.00");
int filingStatus = readInt("Status: ");
switch (filingStatus) {
case 0: double taxableIncomes = readDouble("Please enter your taxable income: ");
if (taxableIncomes <= 8925)
{
tax = (taxableIncomes * TEN);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 8925 && taxableIncomes <= 36250)
{
tax = 892.5 + FIFTEEN * (taxableIncomes - 8925);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 36250 && taxableIncomes <= 87850)
{
tax = 892.5 + 4098.75 + TWENTYFIVE * (taxableIncomes - 36250);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 87850 && taxableIncomes <= 183250)
{
tax = 892.5 + 4098.75 + 12900 + TWENTYEIGHT * (taxableIncomes - 87850);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 183250 && taxableIncomes <= 398350)
{
tax = 892.5 + 4098.75 + 12900 + 26712 + THIRTYTHREE * (taxableIncomes - 183250);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 398350 && taxableIncomes <= 400000)
{
tax = 892.5 + 4098.75 + 12900 + 26712 + 70983 + THIRTYFIVE * (taxableIncomes - 183250);
println("You owe: $" + df.format(tax));
}
if (taxableIncomes > 400000)
{
tax = 892.5 + 4098.75 + 12900 + 26712 + 70983 + 577.5 + THIRTYNINE * (taxableIncomes - 183250);
println("You owe: $" + df.format(tax));
}
break;
into separate methods then call the methods under case:0. For my calculator i'm supposed to use four separate methods and since I have four separate cases I figured the easing thing to do was sort the code for each case into different methods then call those methods for each case that I have. If I try to use
private double tax()
and copy and paste all of the code from under case 0: it tells me that class,interface, or enum expected.

Related

Increase and decrease "money amount" based on win or loss of game

I have made a dice roll game and i'm trying to increase your "cash" by whatever the inputted bet is when you win and remove it when you lose.
import java.util.*;
import javax.swing.JOptionPane;
public class Joption10 {
public static void main(String[] args) {
Random randomNumber = new Random();
//Variables
String name, bet;
int num1, num2;
int cash = 100;
int convertbet;
name = JOptionPane.showInputDialog(null, "Enter Your First Name");
JOptionPane.showMessageDialog(null, "Greetings " + name + ", welcome to roll the dice!" +"\n\nYou will start with " + cash + " euros in your wallet!" + "\n\nThe game ends when you are broke, or when you have doubled your money to 200 euros." + "\n\nGood Luck!");
while (cash > 0 && cash < 200) {
//Generate random numbers for player and dealer
num1 = randomNumber.nextInt(10) + 1; //player
num2 = randomNumber.nextInt(10) + 1; //dealer
bet = JOptionPane.showInputDialog(null, "Place your bet (1 - 100): ");
convertbet = Integer.parseInt(bet);
//Rolling
JOptionPane.showMessageDialog(null, "Rolling the dice...");
if (num2 > num1) {
JOptionPane.showMessageDialog(null, "You Win!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash + 10
} else if (num2 < num1) {
JOptionPane.showMessageDialog(null, "You Lose!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
} else {
JOptionPane.showMessageDialog(null, "No Winner!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
}
JOptionPane.showMessageDialog(null, "You have " + cash + " euros left...");
}
JOptionPane.showMessageDialog(null, "You have won games!");
System.exit(0);
}//Close Main
}//Close Class
If I understand it you should add the convertbet amount when you win and substract it when you loose to the cash.
if (num2 > num1) {
JOptionPane.showMessageDialog(null, "You Win!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash += convertbet
} else if (num2 < num1) {
JOptionPane.showMessageDialog(null, "You Lose!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
cash -= convertbet
} else {
JOptionPane.showMessageDialog(null, "No Winner!" + "\nThe Dealer rolled a " + num1 + "\n" + name + " rolled a " + num2);
}
Watch out you where adding 10 to cash but assigning the returned value nowhere. You can use += operator to add and also assign the value to the variable.

How do I fix my looping for this Single Player Dice Game (4 - 4 sided die)? Issues with Scanner input not yielding correct outputs

// I've been working on this all day but still seem to be stuck.
// I'm not getting any obvious errors but the looping seems to be broken.
// I'm a beginner so its very likely I missed something big but just overlooked it.
// This assignment is due at midnight for my class lol.
// I feel like I constructed the base format decently however my unfamiliarity with using loops is really throwing me for one. I've looked online elsewhere but many of the "dice" programs people have made only pertain to one 6-sided die and do not involve a turn based user input.
// Any useful tips would be fantastic, is there a more efficient way to go about constructing this game? I know creating multiple classes would have cleaned up the look of the program but I'm really only looking for functionality at the moment.
package prgm06;
import java.util.Scanner;
public class DiceGame
{
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
System.out.println("Do you wish to play? [y,n]: ");
do { // I always want the dice to roll unless "n" is selected.
answer = stdIn.next();
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
}
while(answer.equalsIgnoreCase("y")); // issues with "y" not printing if/ else statements
{
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) && (d1 == d3) && (d1 == d4))
{
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
}
else
{
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
}
// do
{
answer = stdIn.next(); // I'm not sure if i need to keep using this at each segment
}
for(answer.equalsIgnoreCase("n");; // will not print on first user input of "n".
{
// System.out.println();
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
if (userWin > userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " Good Job!");
System.out.println(turnCounter + " Rounds played.");
}
else if (userWin < userLose)
{
System.out.println("Your win/loss ratio is: " + (userWin/userLose) + " You shouldn't bet money on this game...");
System.out.println(turnCounter + " Rounds played.");
}
else
{
System.out.println("Your win/loss ratio is: 1.0 .");
System.out.println(turnCounter + " Rounds played.");
}
break;
}
}
}
I've edited your code. Some errors were related to syntax, and some were possibly related to the logical flows. This should work as a base, and you can modify and improve it as you see fit:
import java.util.Scanner;
public class DiceGame {
public static void main(String []args) //main DiceGame loop.
{
String answer;
Scanner stdIn = new Scanner(System.in);
int userWin = 0, userLose = 0, turnCounter = 0;
System.out.println("\t" + "Welcome to Computer Dice");
System.out.println("-----------------------------------------");
System.out.println("The outcome of your roll will determine" + "\n" + "if you win or lose the round." + "\n");
System.out.println("Any Quad and you win.");
System.out.println("Any Triple and you win.");
System.out.println("Any High Pair and you win.");
System.out.println("Anything else and you lose.");
System.out.println("-----------------------------------------");
do { // I always want the dice to roll unless "n" is selected.
System.out.println();
System.out.println("Do you wish to play? [y,n]: ");
answer = stdIn.next();
if (answer.equalsIgnoreCase("y")) {
turnCounter++;
int d1 = (int)(Math.random() * 4) + 1;
int d2 = (int)(Math.random() * 4) + 1;
int d3 = (int)(Math.random() * 4) + 1;
int d4 = (int)(Math.random() * 4) + 1;
System.out.println(d1 + "\t" + d2 + "\t" + d3 + "\t" + d4);
if ((d1 == d2) || (d1 == d3) || (d1 == d4) || (d2 == d3) || (d2 == d4) || (d3 == d4) {
userWin++;
System.out.println("\n" + "Round Results: Win");
System.out.println(turnCounter + " Rounds played.");
} else {
userLose++;
System.out.println("\n" + "Round Results: Loss");
System.out.println(turnCounter + " Rounds played.");
}
System.out.println("Game Results:");
System.out.println("User won: " + userWin + " Games.");
System.out.println("User lost: " + userLose + " Games.");
System.out.println("Your win/loss ratio is: " + userWin + ":" + userLose);
if (userWin > userLose) {System.out.println("Good Job!");}
if (userWin < userLose) {System.out.println("You shouldn't bet money on this game...");}
System.out.println(turnCounter + " Rounds played.");
}
} while(answer.equalsIgnoreCase("y"));
}
}
Some points to note:
The game will keep running as long as the user types in 'y', since that is your condition: answer.equalsIgnoreCase("y").
I changed the win condition logic to check for at least a pair using the logical OR operator
I removed the division operator for the ratio result for win/loss and just replaced it with a display of wins:losses; This could be changed if you want it to calculate for an actual percentage or decimal value, but you have to check for cases where losses == 0 to prevent a divide by zero error
The Do-While loop should encompass all of the gameplay from start to finish, so the question that asks you to play again should go at the start or at the end of this loop (I placed it at the start)

Adding a value to a method using a method

I'm new to OOP and I've hit a brick wall. I have been trying and trying to get a program that enters price houses and adds fees and taxes. The code below is very hard to get to work, I keep running into "cannot find symbol errors" or "possible lossy conversion between double and int" etc. Can you please help me figure what is going wrong with the following class and tester code? This is only a part of the code that I am working on at the moment. Feel free to ask me questions on it and if needed I'll try my best to clarify what I'm trying to do. Thank you.
The class code;
// method that sets the number of houses
public void setAmountOfHouses(int amountOfHouses)
{
//System.out.println("Enter the amount of houses for sale: "); // prompt
if (amountOfHouses > 0) // if the number of houses is valid
this.amountOfHouses = amountOfHouses; // assign it to instance variable number of houses
else
System.out.println("Please add at least 1 house to database... ");
}
// method that returns the number of houses
public int getAmountOfHouses()
{
return amountOfHouses;
}
// method that set the house price
public void setHousePrice(int housePrice)
{
if(housePrice > 0)
{
this.housePrice = housePrice;
}
else
{
System.out.println("Enter a valid house price ");
}
}
// method that returns the house price
public double getHousePrice()
{
return housePrice;
}
//method to calculate fees and taxes
public void calculateFees(int housePrice)
{
if(housePrice > 0 && housePrice <= 100000)
{
housePriceWithTax = housePrice + tax0; // no tax
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
else if(housePrice >= 100001 && housePrice <= 200000)
{
housePriceWithTax = (((housePrice - 100000) * stampDuty1) + housePrice) + tax0;
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
else if(housePrice >= 200001 && housePrice <= 300000)
{
housePriceWithTax = (((housePrice - 200000) * stampDuty2) + housePrice) + tax0 + tax1;
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
else if(housePrice >= 300001 && housePrice <= 400000)
{
housePriceWithTax = ((housePrice - 300000) * stampDuty3) + housePrice + tax0 + tax1 + tax2;
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
else if(housePrice >= 400001)
{
housePriceWithTax = (((housePrice - 400000) * stampDuty4) + housePrice) + tax0 + tax1 + tax2 + tax3;
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
else
{
housePriceWithTax = (((housePrice - 400000) * stampDuty4) + housePrice) + tax0 + tax1 + tax2 + tax3 + tax4;
totalAuctioneerFeeAmount = housePriceWithTax * auctioneerFee;
totalHousePrice = housePriceWithTax + totalAuctioneerFeeAmount;
}
System.out.println("Base house price is: " + housePrice);
System.out.println("Cost of house with tax added is: " + housePriceWithTax);
System.out.println("Total auctioneer fee on this house is: " + totalAuctioneerFeeAmount);
System.out.println("Total cost of house with stamp duty and fees added is: " + totalHousePrice);
}
}
The tester code;
// Entering the amount of houses
System.out.println("\nEnter the amount of houses for sale: "); // prompt
int amountOfHouses = input.nextInt(); // obtain from input
client1.setAmountOfHouses(amountOfHouses);
if(client1.getAmountOfHouses() > 0)
System.out.println("Adding " + client1.getAmountOfHouses() + " houses to database..." );
else
System.out.println("Returning...");
// setting the price of each house
int counter = 0;
do
{
System.out.println("\nEnter the price of each house for sale: ");
int housePrice = input.nextInt();
client1.setHousePrice(housePrice);
System.out.println("\nAdding house price of " + client1.getHousePrice() + " to database");
counter++;
}
while(counter < amountOfHouses);
// calculating fees and taxes
counter = 0;
do
{
client1.calculateFees(client1.getHousePrice());
counter++;
}
while(counter < amountOfHouses);
}
}

Looping program back to ''menu''

I just writed this program, it is to train myself for the upcomming exam this monday.
A thing i would like to add is: after a user is done with one of the exchange options 1/2/3 i would like to give the option to let the user return to the beginning welcome to the money exchange! etc.....
i have tried some a for loop and a while loop but i couldn't get it to work.
Would be cool if after the money exchange process that the user get the option to return to the beginning by typing y or n is this possible?
/* This program is written as a excercise to prep myself for exams.
* In this program the user can:
* 1. Select a currency (other than euro's)
* 2. Input the amount of money
* 3. transfer the amount of currency to euro's
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat() ;
df.setMaximumFractionDigits(2);
int choice = input.nextInt() ;
double transfee = 2.41 ;
double USrate = 0.9083 ;
double GBrate = 1.4015 ;
double YENrate = 0.0075 ;
if (choice > 3 || choice < 1) {
System.out.println("Invalid input!...... Please try agian\n");
} else {
if(choice == 1) {
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble() ;
double deuros = USamount * USrate ;
double ddisburse = deuros - transfee ;
System.out.print("\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ " + df.format(deuros) + "\n");
System.out.print("Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... " + df.format(ddisburse) + "\n" );
}else {
if(choice == 2){
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate ;
double gdisburse = geuros - transfee;
System.out.print("\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ " + df.format(geuros) + "\n");
System.out.print("Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... " + df.format(gdisburse) + "\n");
}else {
if(choice == 3){
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate ;
double ydisburse = yeuros - transfee ;
System.out.print("\nInput amount Yen:... " + YENamount + "\n");
System.out.print("Worth in euro's..... " + df.format(yeuros) + "\n");
System.out.print("Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. " + df.format(ydisburse) + "\n");
}
}
}
}
}
}
You could wrap your program with a while loop, which checks if the user entered 'y' at the end like this:
import java.text.DecimalFormat;
import java.util.Scanner;
class YourClassName
{
public static void main(String[] args)
{
boolean askAgain = true;
while (askAgain)
{
Scanner input = new Scanner(System.in);
System.out.println(
" Welcome to the money exchange! \n Please pick one of the currencies by useing 1 / 2 / 3 \n \n 1 = US dollar \n 2 = GB pounds \n 3 = Yen \n ");
System.out.print("Input : ");
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
int choice = input.nextInt();
double transfee = 2.41;
double USrate = 0.9083;
double GBrate = 1.4015;
double YENrate = 0.0075;
if (choice > 3 || choice < 1)
{
System.out.println("Invalid input!...... Please try agian\n");
} else
{
if (choice == 1)
{
System.out.println("You have choosen for US dollar \n");
System.out.print("Please enter amount US dollar: ");
double USamount = input.nextDouble();
double deuros = USamount * USrate;
double ddisburse = deuros - transfee;
System.out.print(
"\nInput amount US dollar:. " + USamount + "\n");
System.out.print("Worth in euro's:........ "
+ df.format(deuros) + "\n");
System.out.print(
"Transfer cost:.......... " + transfee + "\n");
System.out.print("Amount to disburse:..... "
+ df.format(ddisburse) + "\n");
} else
{
if (choice == 2)
{
System.out.println("You have choosen for GB pounds");
System.out.print("Please enter amount GB ponds: ");
double GBamount = input.nextDouble();
double geuros = GBamount * GBrate;
double gdisburse = geuros - transfee;
System.out.print(
"\nInput amount GB pound:. " + GBamount + "\n");
System.out.print("Worth in euro's........ "
+ df.format(geuros) + "\n");
System.out.print(
"Transfer cost:......... " + transfee + "\n");
System.out.print("Amount to disburse:.... "
+ df.format(gdisburse) + "\n");
} else
{
if (choice == 3)
{
System.out.println("You have choosen for Yen");
System.out.print("Please enter amount Yen: ");
double YENamount = input.nextDouble();
double yeuros = YENamount * YENrate;
double ydisburse = yeuros - transfee;
System.out.print("\nInput amount Yen:... "
+ YENamount + "\n");
System.out.print("Worth in euro's..... "
+ df.format(yeuros) + "\n");
System.out.print(
"Transfer cost:...... " + transfee + "\n");
System.out.print("Amount to disburse:. "
+ df.format(ydisburse) + "\n");
}
}
}
}
System.out.println("Do you want to do another calculation? (y/n)");
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
}
}
}
Setting the boolean variable to true first lets you enter the loop. The user will be asked as long as he types an y at the end. Every other character would exit the loop:
String againAnswer = input.next();
askAgain = againAnswer.equalsIgnoreCase("y");
You could also check for explicit n, but that is up to you.
Put the code inside a while loop (while(true)). At the end of each if block
add one nested if.
System.out.print(Do you want to continue?");
if(in.next().equals("Y")) {
continue;
}
And you have add one extra menu(4th) for exit :
if(choice == 4){
break;
}

if/else statement inside of a while loop

I've written a code for a game that simulates the user and the computer rolling a die and the winner receives 1$ from the loser, with each starting with 2$. The code runs fine, but it doesn't end when either the user or computer reaches 0$ like i had anticipated. Any suggestions?
import java.util.Scanner;
public class ALE_04_RollDice {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")); {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
}while (userMoney >= 0 || compMoney >=0);
}}
Your while statement is testing for <= 0, but initially both variables are > 0. The while loop will never fire.
First off you have a problem with your while condition money values = 2 for player and comp, so while will never fire..fix that and you could use a do while
do{
statement(s) //block of statements
}while (Boolean expression);
So inside your do{} you could have your statements and conditions..so it will do whatever is inside those braces until the condition inside the while() is met
for example
class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
You are using the incorrect condition in the while statement.You are testing if any player has >=0 this will always test true and cause an infinite loop. Instead test if BOTH players have >0 and end the game if not.
Also you have a ';' after you if statement. That will cause the code after it to execute all the time.
Here is complete working code:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userMoney = 2;
int compMoney = 2;
int userRoll = (int) (1 + Math.random() * 6);
int compRoll = (int) (1 + Math.random() * 6);
System.out.print("Press 'r' if you would like to roll ");
do {String roll = input.nextLine();
if (roll.equals("r")) {
if (userRoll > compRoll){
userMoney++;
compMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll + ". you won."
+ "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else if (userRoll < compRoll) {
compMoney++;
userMoney--;
System.out.print("The computer rolled " + compRoll + " and you rolled " + userRoll +
". you lost" + "\n" + "You have $" + userMoney + " & The computer has $" + compMoney);
}
else {System.out.print("The computer rolled " + compRoll + "and you rolled " + userRoll +
". it's a tie" + "\n" + "You have $" + userMoney + " & the computer has $" + compMoney);}
}
//prompt user to type 'r' to roll again
System.out.println("\n\nPress 'r' if you would like to roll ");
}while (userMoney > 0 && compMoney >0);
System.out.println("\n\nGAME OVER!!!");
}
}
//end main
You want to stop when less than or equal to but you have greater than or equal to.
while (userMoney >= 0 || compMoney >=0) {
Cause of problem:
Your while loop does not run at all, because the condition inside is initially evaluated as false.
while (userMoney <= 0 || compMoney <=0)
This reads: whilst the user has a money less than or equal to 0 OR whilst the computer has money less than or equal to 0 then run the while loop, this will never initially be true as they both the computer and user both start with $2, hence userMoney == 2 and compMoney == 2.
Solution:
Change the condition of the while loop to the following:
while(userMoney>0 || compMoney>0)
then add an if statement which says if the compMoney == 0 or if the userMoney == 0, then break out of the while loop.
if(userMoney == 0 || compMoney == 0){
break;
}

Categories