Not adding the customers total correctly - java

So when I run this it does not add the customer total all together. It just keeps displaying the last item entered as the customer total.
import java.util.Scanner;
public class dinerBill {
public static void main(String[] args) {
double taxRate = 0, customerTotal=0, discountType = 0, grandTotal= 0;
Scanner in = new Scanner(System.in);
String [] itemName = { "0) Soup", "1) Wing", "2) Burger", "3) Chicken Sandwich", "4) Fries", "5) Pie", "6) Ice Cream", "7) Soft drink", "8) Coffee"};
double [] itemPrice= {2.50 , .15 , 4.95, 5.95, 1.99, 2.95, 2.99, 1.50, 1.00};
System.out.println("Enter the number of people in the party");
int numberOfPeople = in.nextInt();
while (numberOfPeople >0) {
System.out.println("Enter 1 if customer recieves teen or eldery discount ");
System.out.println("Enter 2 if the customer recieves no discount");
System.out.println("Enter 3 if the customer is under 5");
discountType = in.nextInt();
if (discountType == 1) {
discountType = .85;
taxRate = 1;
}
if (discountType ==2) {
discountType = 1;
taxRate = 1.05;
}
if (discountType ==3)
discountType = 0;
System.out.printf("%-24s", "Menu");
System.out.print("Prices" + "\n");
System.out.println("--------------------------------");
for (int i = 0; i < itemName.length; i++) {
System.out.printf("%-24.21s" ,itemName[i]);
System.out.print(itemPrice[i] +"\n");
}
System.out.println("Enter the corresponding number");
for (int choices=3; choices > 0; choices--) {
double choicePrice = 0 , customerTotalBeforeDiscount = 0;
System.out.println("Enter customers item");
int customerItem = in.nextInt();
if (customerItem ==1) {
System.out.println("How many wings ordered?");
int wingsOrdered = in.nextInt();
double priceOfWings = wingsOrdered * itemPrice[1];
choicePrice = priceOfWings;}
else
choicePrice = itemPrice[customerItem];
customerTotalBeforeDiscount +=choicePrice;
double customerTotalBeforeTax = customerTotalBeforeDiscount * discountType;
customerTotal = customerTotalBeforeTax * taxRate;
}
System.out.print("The total for the customer is $" );
System.out.printf("%.2f \n" , customerTotal );
grandTotal += customerTotal;
numberOfPeople--;
}
System.out.print("The total is $");
System.out.printf("%.2f", grandTotal);
in.close();
System.exit(0);
}
}
Here are the results that I'm getting:
Enter the number of people in the party
1
Enter 1 if customer recieves teen or eldery discount
Enter 2 if the customer recieves no discount
Enter 3 if the customer is under 5
2
Menu Prices
--------------------------------
0) Soup 2.5
1) Wing 0.15
2) Burger 4.95
3) Chicken Sandwich 5.95
4) Fries 1.99
5) Pie 2.95
6) Ice Cream 2.99
7) Soft drink 1.5
8) Coffee 1.0
Enter the corresponding number
Enter customers item
0
Enter customers item
0
Enter customers item
0
*The total for the customer is $2.6*3
The total is $2.63

Your problem is in
double choicePrice = 0 , customerTotalBeforeDiscount = 0;
because it resets customerTotalBeforeDiscount on each iteration. Instead do:
double customerTotalBeforeDiscount = 0;
for (int choices=3; choices > 0; choices--) {
double choicePrice = 0;

well after looking at it , the customer total did reset to 0, after I fixed that, I noticed that it was =+ and not +=.
customerTotalBeforeDiscount =+ choicePrice;
customerTotalBeforeDiscount += choicePrice;
so yes yours was right but somehow I got the += changed when it was correct in my original post.

Related

Trying to find the best way to re-access code

I'm creating a gambling application with 2 games. However I want to be able to switch from one game to the next. I tried if(game == 1), but it seemed that once I matched the condition, it exited the loop and trying to take input again would not switch to the second game. Then I tried do while but even when I set my input to "2" it still starts game #1. Any suggestions on what I should do?
import java.util.Scanner;
import java.util.Random;
public class Project2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int min = 1;
int max = 10;
int colmax = 2;
double balance = 2500;
double bet1 = 0;
double bet2 = 0;
String kBet = null;
//Call method gameChoice to allow player to choose what game they want to play.
gameChoice();
int game = input.nextInt();
do {
System.out.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-BLACK JACK-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
System.out.print("Please choose Black or Red, and a number from 1-10..(Example: Red 4): ");
String color = input.next();
int number = input.nextInt();
//Seperate bets for color and number. Bet1 = color bet, bet2 = number bet
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+color+"?");
bet1 = input.nextInt();
if(bet1 > balance) {
System.out.print("You dont have enough money to bet $"+bet1+". Please enter a valid bet: $");
bet1 = input.nextInt();
}
else
balance -= bet1;
double profit1 = (bet1 * 2) - bet1;
//Bet 2 for number.
System.out.print("Your available balance is $"+balance+". How much would you like to bet on "+number+"?");
bet2 = input.nextInt();
if(bet2 > balance) {
System.out.print("You dont have enough money to bet $"+bet2+". Please enter a valid bet: $");
bet2 = input.nextInt();
}
else
balance -= bet2;
double profit2 = (bet2 * 5) - bet2;
//Give bet info
System.out.println("------------------------------BET INFO------------------------------------");
System.out.println("You just bet $"+bet1+" on "+color+" and $"+bet2+" on number "+number);
System.out.println("Spinning............");
System.out.println("------------------------------RESULTS-------------------------------------");
//Generate random number, Generate random color.
Random rouletteNum = new Random();
int rNum = min + rouletteNum.nextInt(max);
int rCol = min + rouletteNum.nextInt(colmax);
//Only generate 2 numbers between 1-2; 1 is black, 2 is red.
if (rCol == 1) {
System.out.println("The machine landed on Black "+rNum);
}
else if(rCol != 1) {
System.out.println("The machine landed on Red "+rNum);
}
//All possible conditions for betting outcomes.
if(rNum == number) {
System.out.println("Congrats, you guessed the right number! You've won $"+profit2);
balance += (bet2 * 5);
}
else if(rNum != number) {
System.out.println("Sorry!You didnt guess the right number! You've lost $"+bet2);
}
if(rCol == 1 && color.equals("Black")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
else if(rCol == 2 && color.equals("Red")) {
System.out.println("Congrats, you guessed the right color! You've won $"+profit1);
balance += bet1 * 2 - bet1;
}
if(rCol == 2 && color.equals("Black")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
else if(rCol == 1 && color.equals("Red")) {
System.out.println("Sorry, you didn't guess the right color. You've lost $"+bet1);
}
System.out.println("------------------------------------------------------------------------");
//Call isBroke method to check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If player isn't bankrupt, ask if they want to place another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 1);
{
do {
int bet = 0;
double start = 1.00;
double crashValue = 1.00;
int stopGame = 1;
double cashout = 0;
System.out.println("-------------------CRASH GAME--------------------------");
System.out.println("Welcome to Crash!");
System.out.print("What number would you like to cashout at?(Ex. 1.15):");
cashout = input.nextDouble();
System.out.print("Your balance is $"+balance+". How much would you like to bet on this round?:");
bet = input.nextInt();
//check if bet amount is greater then the balance.
if(bet > balance) {
System.out.print("You dont have enough money to bet $"+bet+". Please enter a valid bet: $");
bet = input.nextInt();
}
else
System.out.println("--------------------------------------------------------------------------");
System.out.println("Round is beginning.........");
for(int i =0; i < stopGame; i++) {
//Do while to keep the numbers generating until i == 1 (until crash)
do {
//Generate random number from 1-100, if the number is less than 98, print the digit (Example : 1.34)
int crash =(int)(Math.random() * 100);
if (crash < 98) {
start += .01;
System.out.printf("%.2f\n",start);
}
//if random number from 1-100 is greater than 98, crash the game.
else if(crash > 98) {
i++;
crashValue = start;
System.out.println("----------------------------RESULTS--------------------------------");
System.out.print("CRASH! The game crashed at ");
System.out.printf("%.2f",start);
System.out.println("x");
}
}
while(i == 0);
}
//Check if player cashed out before game crashed.
if(cashout < crashValue) {
System.out.println("Congrats! You cashed out at "+cashout+" before the game crashed. You've won $"+bet*cashout);
balance += bet * cashout;
}
//Player didn't cash out in time, and lost.
else {
System.out.println("Sorry! The game crashed before you could cash out. You've lost $"+bet);
balance -= bet;
}
System.out.println("------------------------------------------------------------------------");
//check if player is bankrupt.
if(isBroke(balance) == true) {
endGame(balance);
}
else {
//If they arent bankrupt, ask if they want another bet.
System.out.println("New balance: $"+balance);
gameChoice2();
game = input.nextInt();
}
}
while(game == 2);
}
You've used a do...while loop. This type of loop always executes its body at least once before evaluating the while condition.

Java Loan Calculator nested for loop based on user input

The task is to create a loan calculator based on the user input of min and max years of loan payments, loan amount, and min and max % rate with incremented value given by user as well for rate and number of years.
Desired output should look like this:
Principle: $275000.0
Years to repay: 10
Interest Monthly
Rate Payment
6.25 3087.7
6.75 3157.66
7.25 3228.53
Principle: $275000.0
Years to repay: 15
Interest Monthly
Rate Payment
6.25 2357.91
6.75 2433.5
7.25 2510.37
Principle: $275000.0
Years to repay: 20
Interest Monthly
Rate Payment
6.25 2010.05
6.75 2091.0
7.25 2173.53
Please help me fix errors. Thanks!
public static void main(String[] args){
Scanner console = new Scanner (System.in);
System.out.println("This program computes monthly " + "mortgage payments.");
System.out.print("Enter the loan amount: ");
double loan = console.nextDouble();
System.out.print("Enter the starting number of years to repay the loan: ");
int startingYears = console.nextInt();
System.out.print("Enter the ending number of years to repay the loan: ");
int endingYears = console.nextInt();
System.out.print("Enter the years increment between tables: ");
int incrementYears = console.nextInt();
System.out.print("Enter the starting loan yearly interest rate, %: ");
double startingRate = console.nextDouble();
System.out.print("Enter the ending loan yearly interest rate, %: ");
double endingRate = console.nextDouble();
System.out.print("Enter the increment interest rate, %: ");
double incrementRate = console.nextDouble();
System.out.println();
System.out.println("Principle: $" + (double) loan);
System.out.printf("Years to repay: %d\n", startingYears);
System.out.println("-------- -------");
double payment;
System.out.println("Rate\tPayment");
for (int j = startingYears; j <= endingYears; incrementYears++) {
for (double i = startingRate; i <= endingRate; incrementRate++){
int n = 12 * startingYears;
double c = startingRate / 12.0 / 100.0;
payment = loan * c * Math.pow(1 + c, n) / (Math.pow(1 +c, n) - 1);
System.out.println(i + " " + payment);
// System.out.println(round2(startingRate) + "\t" + round2(payment));
startingYears += incrementYears;
}
}
}
}
for (int j = startingYears; j <= endingYears; incrementYears++) {
for (double i = startingRate; i <= endingRate; incrementRate++) {
You are never incrementing the values of your counters i.e. i and j and hence the values of i and j will always be equal to the initialized values and these loops will run for infinite times.
Increment both the counters to be able to reach the termination condition i.e. j <= endingYears and i <= endingRate respectively.
Here is the code snippet:
System.out.println("Principle: $" + (double) loan);
for (int j = startingYears; j <= endingYears; j+=incrementYears) {
System.out.printf("Years to repay: %d\n", j);
System.out.println("-------- -------");
System.out.println("Rate\tPayment");
for (double i = startingRate; i <= endingRate; i+=incrementRate){
int n = 12 * j;
double c = i / 12.0 / 100.0;
double payment = loan * c * Math.pow(1 + c, n) / (Math.pow(1 + c, n) - 1);
System.out.println(i + "\t" + payment);
}
System.out.println();
}

Java getting average after total per index

I'm trying to figure out how to implement a total of my SCORES and VOTES which I have done no problem. Where I'm getting confused and can't seem to solve is how I would go back through my array of Contestants and get their percent of the total SCORES or VOTES. e.g player 1 has a score of 10 out of a total score of 30, player 2 has a score of 15/30 ect... a running average is not a problem its a real total average I can't seem to wrap my head around. Any advice would be terrific.
package contestscore;
import java.util.*;
public class ContestScore {
public static void main(String[] args) {
// TODO code application logic here
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter number of contesants: ");
int numContest = keyboard.nextInt();
System.out.println("Enter contestants DANCE SCORE and NUMBER OF VOTES EARNED: ");
int[] danceScore = new int[numContest+1];
int[] numVotes = new int[numContest+1];
double avgDanceScore = 0.0;
double avgVoteScore = 0.0;
double totalDanceScore = 0.0;
int numContestIndex = 0;
double avgContestDanceScore = 0.0;
int totalVotes = 0;
double avgContestVote = 0.0;
for(numContestIndex = 1; numContestIndex <= numContest; numContestIndex++)
{
danceScore[numContestIndex] = keyboard.nextInt();
numVotes[numContestIndex] = keyboard.nextInt();
System.out.println("DANCE SCORE: "+danceScore[numContestIndex]);
System.out.println("NUMBER OF VOTES: "+numVotes[numContestIndex]);
totalDanceScore = totalDanceScore + danceScore[numContestIndex];
//avgContestDanceScore = danceScore[numContestIndex] /totalDanceScore;
System.out.println("TOTAL DANCE SCORE: "+totalDanceScore);
totalVotes = totalVotes + numVotes[numContestIndex];
//avgContestVote = numVotes[numContestIndex] / totalVotes;
System.out.println("TOTAL CONTESTANT VOTE SHARE: "+totalVotes);

Unreachable code, compilation error vicious circle

So I have made a programme that calculates the cost of of a ticket based on a number of factors I'll post the question i got below
Create a program that given a number of tickets (maximum of 10),
the type of ticket (return, one way), the passenger type (under 10, under 16,
student, over 60, other), the selected route, and the starting and finishing
stops (in the form of a number where n denotes stopn ),
calculates the total cost for the journey.
The cost of each ticket should be calculated as follows:
• The cost per mile is 50p;
• Under 10 travel free when accompanied by an adult;
otherwise, a discount of 75% is applied;
• Under 16 get a 50% discount;
• Students get a 25% discount;
• Over 60’s get a 60% discount.
Train routes should be expressed in the format:
int [n] route = {stop2 , stop3 , ... stopNPlusOne};
Example:
int [4] route1 = {3, 5, 2, 6};
denotes a route with 5 stops:
the distance between stop one and two is 3 miles,
between stop two and three is 5 miles,
between stop three and four is 2,
and between stop four and five is 6.
My code is as follows
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of Tickets (Max 10): ");
int numberOfTickets = input.nextInt();
if (numberOfTickets > 10) {
System.out.println("Please choose less than 10 tickets");
} else {
double cost = route();
double totalCost = (cost * numberOfTickets);
System.out.println("");
System.out.printf("Your total cost is:", totalCost);
}
}
// DECLARE A NEW METHOD THAT CALCULATES THE DISTANCES TRAVELLED
public static double route() {
Scanner input = new Scanner(System.in);
int[] route = { 7, 12, 13, 17, 22, 26 }; // miles between each stop
System.out.println("Enter the first station number(0 - 5): ");
int firstStation = input.nextInt();
System.out.println("Enter the last station number(0 - 5): ");
int lastStation = input.nextInt();
int totalMiles = 0;
for (int i = firstStation; i < lastStation; i++) {
totalMiles = totalMiles + route[i]; // Total miles
}
System.out.println(totalMiles);
double cost = totalMiles * 0.5; // (* 0.5) because it's 50p per mile.
System.out.println("The initial cost is £" + cost);
System.out.println("Please enter your age");
int age = input.nextInt();
double totalCost = 0;
int adults = 0;
return adults;
{
{
if ((age < 10) && (age > 0)) {
cost = (cost * 0.25);
} else if ((age < 16) && (age >= 10)) {
cost = (cost * 0.5);
} else if (age > 60) {
cost = (cost * 0.4);
}
System.out.println("Are you a student, if yes enter 1 if not enter 2");
int studentPass = input.nextInt();
boolean Student = false;
if (studentPass == 1)
{
Student = true;
}
if (studentPass == 2) {
adults++;
}
return cost;
}
}
}
}
}
The issue is there is an error on the last curly bracket and so when i delete it everything from return adults and down is said to be unreachable code.
Apologies for the vast amount of text in the question. I'm in java by the way.
The problem is that you have multiple returns in the same function. When a return executes the function exits meaning that the code below will never be able to be run and thus it is unreachable.
So in this:
public int function(){
value = 0
//do stuff
return value
//do more things
}
"do more things: will never be able to be run because the function stops running as soon as return value is encountered. This code is said to be unreachable.
Put your code in multiple functions, each with only one return, and then call those functions from your main or wherever you want to use them as necessary

Check if integers within an array are within the range

Basically, the program I am supposed to write is to get the energy usage from the customer for 12 months and then output the total usage, price for two tariffs (the formulas are included in the code) and say which tariff is cheaper. But it also has to check whether the input for each of those 12 months is within the range (greater than "0" AND less or equal to "1000").
I have found a fairly easy(?) way to do it using arrays, however I have no idea how to check whether each one of the integers scanned to be in that array are actually within the range 0 < int <= 1000
If the integer is less than 0 or greater than 1000, the program has to output a line "Please enter a valid amount" and ask for the same integer again, so that it doesn't store the wrong value, if it makes sense?
import java.util.Scanner;
public class EnergyConsumptionExample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total_usage;
float t1_cost, t2_cost;
final int MAX_USAGE = 1000, MIN_USAGE = 0;
int[] energyCons = new int[12];
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
energyCons[month] = scan.nextInt();
}
int totalCons = 0;
for (int month = 0; month < energyCons.length; month++) {
totalCons += energyCons[month];
}
System.out.println();
System.out.println("Total usage for the year was " + totalCons + " kWh");
t1_cost = (float) (totalCons * 0.1);
t2_cost = (float) ((totalCons * 0.09) + 50);
System.out.println("Using tariff one, the cost is: " + t1_cost);
System.out.println("Using tariff two, the cost is: " + t2_cost);
System.out.println();
if (t1_cost > t2_cost) {
System.out.println("Tariff two would be cheaper for this customer.");
} else {
System.out.println("Tariff one would be cheaper for this customer.");
}
}
}
Change your input reading loop to something like this:
for (int month = 0; month < energyCons.length; month++) {
System.out.print("Please enter the monthly kWh usage for month ");
System.out.print((month + 1) + ": ");
int inputValue = scan.nextInt();
while (inputValue < 0 || inputValue > 1000) {
System.out.println("Please enter a valid amount: ");
inputValue = scan.nextInt();
}
energyCons[month] = inputValue;
}

Categories