This is my first post here, so forgive me for any formatting errors.
So as you can see my program requests the gender, # of accidents and year of car to display a fictitious insurance quote.
Based on all that information I need to add the subtotal of the insurance cost to the end.
I have my code working up until the Total Cost comment (posted it all for reference). I am stuck there because the genders have different base amounts. I'm trying to figure out a way to only do one if statement if it matches the gender that was input by the user.
Any ideas?
import java.util.*;
public class Insurance {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
int currentYear = 2017; //used for calculating the age of the users car
int maleGender = 1000;
int femaleGender = 500;
//Letting user know they are inputting data for car insurance purposes
System.out.println("Car insurance questionnaire. Please input correct information when prompted.");
// gender information from user
System.out.println("What is your gender? m/f");
String gender = scanner.next();
// accident quantity information from user
System.out.println("How many accidents have you had?");
int acc = scanner.nextInt();
// car year information from user
System.out.println("What year was your car manufactured?");
int carAge = scanner.nextInt();
//if statements which refer to the users data input
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
} else {
System.out.println("You are a female.\nThe base cost is $500.");
}
if (acc == 0) {
System.out.println("You have no accidents. Insurance increase is $0.");
} else if (acc >= 1) {
System.out.println("You have " + acc + " accidents. Insurance increase is $" + acc * 100 + ".");
}
if (carAge >= 2007) {
System.out.println("Your car is " + (currentYear - carAge) + " years old.\nYour car is still in warranty, no savings added.");
} else
System.out.println("Your car is out of warranty, final cost is halved.");
//Total cost
/*
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + femaleGender) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + femaleGender) + ".");
*/
}
}
I am not totally sure how you want to calculate your result but if do NOT want to use femaleGender all the time but in dependency of the gender different values then maybe something like this could help:
int baseAmount = gender.equals("m") ? maleGender : femaleGender;
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + baseAmount ) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + baseAmount ) + ".");
}
int genderCost;
...
if (gender.equals("m")) {
System.out.println("You are a male.\nThe base cost is $1000.");
genderCost = maleGender;
} else {
System.out.println("You are a female.\nThe base cost is $500.");
genderCost = femaleGender;
}
...
if (carAge <= 2007) {
System.out.println("Your total price is $" + ((acc * 100 + genderCost) / 2) + ".");
} else
System.out.println("Your total price is $" + (acc * 100 + genderCost) + ".");
}
Put the amount for gender in a variable genderCost when the gender input variable is evaluated and use genderCost when you calculate the total.
Related
This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 6 years ago.
Need help with if else statement in Java. Need the program to say "Sorry, out of stock" when items are at 0. I tried but it wont print out "Sorry, out of stock" Can anyone explain to me how to properly set that up so when the items are at 0 the program will let the user know that the item is out of stock. Thank you.
import java.util.Scanner;
public class VendingMachine {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int Chips = 5;
int Cookies = 4;
int Candies = 3;
double ChipsPrice = 1.25;
double CookiesPrice = 0.85;
double CandiesPrice = 0.95;
Scanner choice = new Scanner(System.in);
Scanner moneyIn = new Scanner(System.in);
while (true) {
double Change = 0;
double Amount = 0;
double Money = 0;
System.out.println("Welcome to the Vending Machine");
System.out.println("Please insert Money");
Amount = moneyIn.nextDouble();
//Make an if statements, such as if moneyIn equals 5 quarters then Amount = 5*0.25
//Ask how many quarters how many nickels how many dimes
System.out.println("What snack would you like?");
System.out.println("Potato Chips: $" + ChipsPrice + " " + Chips + " left");
System.out.println("Cookies: $" + CookiesPrice + " " + Cookies + " left");
System.out.println("Candies: $" + CandiesPrice + " " + Candies + " left");
String which = choice.nextLine();
if (which.equals("Potato Chips")) {
System.out.println("You selected Potato Chips: $" + ChipsPrice + " " + Chips + " left");
if (Amount < ChipsPrice) {
System.out.println("Not enough money inserted");
if (Chips == 0) ;
System.out.println("Sorry, out of stock");
} else {
Chips = Chips - 1;
Change = ChipsPrice - Amount;
System.out.println("Please take your chips ");
System.out.println("Your change is " + Change);
}
} else if (which.equals("Cookies")) {
System.out.println("You selected Cookies: $" + CookiesPrice + " " + Cookies + " left");
Cookies = Cookies - 1;
if (Amount < CookiesPrice) {
System.out.println("Not enough money inserted");
if (Cookies == 0)
System.out.println("Sorry, out of stock");
} else {
Cookies = Cookies - 1;
Change = CookiesPrice - Amount;
System.out.println("Please take your cookies");
System.out.println("Your change is " + Change);
}
} else if (which.equals("Candies")) {
System.out.println("You selected Candies: $" + CandiesPrice + " " + Candies + " left");
if (Amount < CandiesPrice) {
System.out.println("Not enough money inserted");
if (Cookies == 0)
System.out.println("Sorry, out of stock");
} else {
Candies = Candies - 1;
Change = CookiesPrice - Amount;
System.out.println("Please take your candies");
System.out.println("Your change is " + Change);
}
} else {
System.out.println("Please select one of the snacks below");
}
}
}
}
Just to go through this, a few observations:
// It might be simpler to use a "switch" statement here
if (which.equals("Potato Chips")) {
System.out.println("You selected Potato Chips: $"+ChipsPrice+" "+Chips+" left");
if (Amount < ChipsPrice){
System.out.println("Not enough money inserted");
// Remove the semicolon - as written this won't do anything
// Also, this condition shouldn't be here since you're not vending anyway
// Incidentally, many people argue that you should always use curly
// brackets, even around one-line "if" statements like this, precisely
// to prevent errors like this
if (Chips == 0);
System.out.println("Sorry, out of stock");
}
else {
// This can be written as Chips--;
Chips = Chips - 1;
// Should actually be Amount - ChipsPrice;
// If they paid 75 cents for a 25-cent item, the change is 75 - 25 = 50 cents,
// NOT 25 - 75 = -50 cents
Change = ChipsPrice - Amount;
System.out.println("Please take your chips " );
System.out.println("Your change is "+ Change );
}
}
else if (which.equals("Cookies")) {
System.out.println("You selected Cookies: $"+CookiesPrice+" "+Cookies+" left");
// Cookies--
Cookies = Cookies - 1;
if (Amount < CookiesPrice){
System.out.println("Not enough money inserted");
// Should be checked in the "else" statement
if (Cookies == 0)
System.out.println("Sorry, out of stock");
}
else {
// Cookies--
Cookies = Cookies - 1;
// Amount - CookiesPrice
Change = CookiesPrice - Amount;
System.out.println("Please take your cookies");
System.out.println("Your change is "+ Change );
}
}
else if (which.equals("Candies")) {
System.out.println("You selected Candies: $"+CandiesPrice+" "+Candies+" left");
if (Amount < CandiesPrice){
System.out.println("Not enough money inserted");
// Again, you shouldn't check this here given that you won't vend either way
// Also, should be if (Candies == 0), NOT if (Cookies == 0)
if (Cookies == 0)
System.out.println("Sorry, out of stock");
}
else {
// Candies--;
Candies = Candies - 1;
// Should actually be Amount - CandyPrice. You use CookiesPrice instead.
Change = CookiesPrice - Amount;
System.out.println("Please take your candies");
System.out.println("Your change is "+ Change );
}
}
else {
System.out.println("Please select one of the snacks below");
}
One more thing: you're basically doing the same exact thing 3 consecutive times; in situations like that, it's usually better to try to refactor the behavior in question as a method (rather than typing it 3 separate times).
I'm trying to print out different variables I've already declared in different switch cases, they're all in one switch block in a for loop but the compiler isn't allowing me use the variables. Giving me a "cannot find symbol" error.
Here's the code:
public static void main(String[] args) {
double hammer = 3.25, nails = 5.25, paint = 4.75, paintBrush = 2.25, balance = 50.00;
Scanner input = new Scanner(System.in);
System.out.println("Local Hardware Point of Sales");
System.out.println("\t::MENU::");
System.out.println("1. Purchase Items\n2. Display current purchases\n3. Display account balance\n4. Complete transactions and Exit");
System.out.print("Enter choice: ");
int choice = input.nextInt();
switch(choice){
case 1:
for(int i = 0; i <= 2; i++){
System.out.println("\n\tPurchase Items");
System.out.println("What items would you like to purchase?");
System.out.println("\tItems \t\tPrices");
System.out.println("\tHammer\t\t-$3.25\n\tNails\t\t-$3.25\n\tPaint\t\t-$3.25\n\tPaint Brush\t-$3.25");
String item = input.next();
switch (item) {
case "Hammer":
case "hammer":
System.out.println("How many Hammers would you like to purchase?");
int hItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double hPrice = hItem*hammer;
System.out.println("Cost for " + hItem + " Hammers: $" + hPrice);
double hBalance = balance - hPrice;
System.out.println("Final Balance: $" + hBalance);
if(hBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ hItem+ " Hammers (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+hItem+"Hammers for "+ hPrice);
}
}
break;
case "Nails":
case "nails":
System.out.println("How many Nails would you like to purchase?");
int nItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double nPrice = nItem*nails;
System.out.println("Cost for " + nItem + " Nails: $" + nPrice);
double nBalance = balance - nPrice;
System.out.println("Final Balance: $" + nBalance);
if(nBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ nItem+ " Nails (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+nItem+" Nails for "+ nPrice);
}
}
break;
case "Paint":
case "paint":
System.out.println("How many Paints would you like to purchase?");
int pItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pPrice = pItem*nails;
System.out.println("Cost for " + pItem + " Paints: $" + pPrice);
double pBalance = balance - pPrice;
System.out.println("Final Balance: $" + pBalance);
if(pBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pItem+ " Paints (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pItem+" Paints for "+ pPrice);
}
}
break;
case "Paint Brush":
case "paint brush":
System.out.println("How many Paint Brushes would you like to purchase?");
int pbItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pbPrice = pbItem*nails;
System.out.println("Cost for " + pbItem + " Paint Brushes: $" + pbPrice);
double pbBalance = balance - pbPrice;
System.out.println("Final Balance: $" + pbBalance);
if(pbBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pbItem+ " Paint Brushes (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pbItem+" Paint Brushes for "+ pbPrice);
}
}
break;
default:
break;
}
System.out.println("\nMake another purchase? (Y/N)");
String ans = input.next();
if(ans.equals("n"))
System.out.println("\tCurrent Receipt");
System.out.println("Items \t\tQuantity \t\tPrice Per \t\tTotal Price");
System.out.println("Hammer \t\t"+**hItem**+" \t\t\t"+hammer+" \t\t\t"+**hPrice**);
System.out.println("Nails \t\t"+**nItem**+" \t\t\t"+nails+" \t\t\t"+**nPrice**);
System.out.println("Paint \t\t"+**pItem**+" \t\t\t"+paint+" \t\t\t"+**pPrice**);
System.out.println("Paint Brush \t\t"+**pbItem**+" \t\t\t"+paintBrush+" \t\t\t"+**pbPrice**);
}
}
}
}
I bolded the variables that are giving the error. P.s I am not allowed to use methods for this project, strictly conditional statements and loops.
Also if anyone doesn't mind, I'm trying to get string input for "Paint Brush" but using input.next() has issues with the space, and when I used input.nexLine() it completely ignored the input and ended the program, so had to revert back to next().
Please if anyone can help, much appreciated. Thanks alot
Declare the variables that give you an error outside of the switch-case. Currently their scope is limited to only the inside of the case part, meaning that for the rest of the code (outside of the case) they don't exist.
So I have been trying to figure this out for the past 5 hours and the reason being...from a beginner point of view this code looks fine with no errors but the output is still wrong...basically for every 10 kids tickets the user gets one free,so the output is fine if the free tickets is less than the adults but it subtracts the extra adults when its the other way around.
package theatre;
import java.util.*;
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int Adult = kybd.nextInt();
System.out.println("Child: ");
int Child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
System.out.println(freeAdult); //reference out
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
}
}
Thanks
I think you have your logic a little confused:
int freeAdult = Child / 10;
if (freeAdult < 9) {
System.out.println("You get " + freeAdult + " adult tickets");
} else {
System.out.println("You don't get any free tickets");
}
appears to be calculating how many free adult tickets the person gets based on the number of child tickets (Child / 10) ...but is then saying they get no tickets if they've qualified for more than 10? I think you might be using the wrong variable here. Then:
double adultBill = (Adult * 10.50) - (freeAdult * 10.50);
double childBill = Child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
double totalBill2 = childBill + concessionsBill;
System.out.println(totalBill2); //reference out
if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
} else {
System.out.println("Please enter a corrrect value");
}
I believe is meant to calculate 2 bills, one including adults and one not and then if the number of free adult tickets is greater than the number of adults, discard the first bill and use the second (which never included the adults calculation), in which case you have your if statement the wrong way around, it should be:
if (freeAdult < Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill);
} else if (freeAdult >= Adult) {
System.out.printf("Total bill is: £%.2f\n", totalBill2);
...however you should only have to calculate one bill by simply changing the adult calculation to:
double adultBill = freeAdult < Adult ? (Adult * 10.50) - (freeAdult * 10.50) : 0;
Then calculate bill as normal:
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
public class Theatre {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter the number of tickets you would like to buy for each type: ");
System.out.println("Adult: £10.50");
System.out.println("Child: £7.30");
System.out.println("Concessions £8.40");
System.out.println("Adult: ");
int adult = kybd.nextInt();
System.out.println("Child: ");
int child = kybd.nextInt();
System.out.println("Concessions: ");
int concessions = kybd.nextInt();
int freeAdult = child / 10;
System.out.println("You get " + freeAdult + " adult tickets free");
if(adult >0){
adult = adult - freeAdult;
}
double adultBill = (adult * 10.50);
double childBill = child * 7.30;
double concessionsBill = concessions * 8.40;
double totalBill = adultBill + childBill + concessionsBill;
System.out.printf("Total bill is: £%.2f\n", totalBill);
}
}
I have just started learning Java in a college course. If/then statements haven't been covered yet but I figured I could try them on my own. I ended up with some syntax errors which I think I fixed, but now it seems like there are operand errors when I try adding a string with integers.
The problem given in my class was to ask the user for their name, hourly rate of pay, and how many hours they worked. I know the professor will soon ask us to ask the user if they get paid overtime. If they do, ask after how many hours overtime is paid. And then calculate the total payment, with any overtime pay being 1.5x of the regular hourly rate.
However I get an error in the last 3 print statements, which I assume is because I am trying to combine a string and an integer. How do I fix this?
package javaapplication2;
import java.util.Scanner;
public class JavaApplication2 {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
String name;
double payRate;
int hours;
Boolean OTyn;
int OTy;
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("What is your hourly rate of pay?");
payRate = input.nextDouble();
System.out.println("How any hours have you worked?");
hours = input.nextInt();
System.out.println("Your boss pays overtime. Answer with true or false.");
OTyn = input.nextBoolean();
if (OTyn == true)
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy)
System.out.println("Your weekly pay is " + ((40 * payRate) + (hours - OTy)(payRate * 1.5)));
else
System.out.println("Your weekly pay is " + payRate * hours);
else
System.out.println("Your weekly pay is " + payRate * hours);
}
}
I think you are missing the {} on the ifs
if (OTyn == true) { //here
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy){ // Here doesn need because it is just one line after the if
System.out.println("Your weekly pay is " +
((40*payRate) + (hours - OTy)(payRate*1.5)));
// (hours - OTy)(payRate*1.5) you are missing an operator between this expressions
}else{
System.out.println("Your weekly pay is " + payRate*hours);
}
} else { //here
System.out.println("Your weekly pay is " + payRate*hours);
} //and here
Plus for an IF statement that has just one line after it you doesn't need the {} as this:
if ( something )
System.out.println("Something is true");
else
System.out.println("Something is false");
You were missing one set of braces and an asterisk as follows.
if (OTyn == true) { // <-- This brace to open.
System.out
.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy)
System.out.println("Your weekly pay is "
+ ((40 * payRate) + (hours - OTy)
* (payRate * 1.5))); // <-- at the start of this line.
else
System.out.println("Your weekly pay is "
+ payRate * hours);
} else // <-- That brace to close.
System.out.println("Your weekly pay is "
+ payRate * hours);
import java.util.Scanner;
public class JavaApplication2
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
double payRate;
int hours;
Boolean OTyn;
int OTy;
System.out.println("What is your name?");
name = input.nextLine();
System.out.println("What is your hourly rate of pay?");
payRate = input.nextDouble();
System.out.println("How any hours have you worked?");
hours = input.nextInt();
System.out.println("Your boss pays overtime. Answer with true or false.");
OTyn = input.nextBoolean();
if (OTyn == true){
System.out.println("After how many hours are you paid for overtime?");
OTy = input.nextInt();
if (hours > OTy){
System.out.println("Your weekly pay is " + ((40*payRate) + (hours - OTy)*(payRate*1.5)));
}
else{
System.out.println("Your weekly pay is " + payRate*hours);
}
}
else {
System.out.println("Your weekly pay is " + payRate*hours);
}
}
}
Try this, not only were you missing braces, you also had a problem with this line
System.out.println("Your weekly pay is " + ((40*payRate) + (hours - OTy)(payRate*1.5)));
you need a * between (hours - OTy) and (payRate*1.5)to result in (hours - OTy)*(payRate*1.5) otherwise the string concatenation will not work
Is there a way to make it so I can sort through an ArrayList output the highest number found along with the lowest number found? The way I have it now is a "shoppinglist" which is set up like this:
public void addToBag(String anyItem, int anyUnits, double anyCost){
int checkUnits = anyUnits;
double checkCost = anyCost;
if(checkUnits < 0 || checkCost < 0){
System.out.println("You must enter a value equal to or greater than 0!");
}else{
shoppingBag.add(new Item(anyItem, anyUnits, anyCost));
}
}
and the output which only outputs the list
public void calculateSalesReceipt(){
System.out.println("Enter the sales tax percentage (ex. 0.08 for 8%) or type \"random\" for a random number: ");
double tax = keybd.nextDouble();
if(tax < 0){
System.out.println("You must enter a value equal to or greater than 0!");
}else{
getPricePreTax();
total = total;
taxCost = total * tax;
finaltotal = total + taxCost;
System.out.println("Sales Receipt");
System.out.println("-------------");
for(Item currentProduct : shoppingBag){
System.out.println(currentProduct.getName() + " - " + currentProduct.getUnits() + " units " + " - $" + currentProduct.getCost());
}
System.out.println("Total cost: $" + total);
System.out.println("Total tax: $" + taxCost);
System.out.println("Total cost with tax: $" + finaltotal);
System.out.println("Do you have any coupons? Enter \"yes\" or \"no\"");
String answer = keybd.next();
if(answer.equals("yes")){
applyCoupon();
}else if(answer.equals("no")){
System.out.println("Thank you!");
}else if(answer != "yes" || answer != "no"){
System.out.println("Thank you!");
}
System.out.println("Coupon discounts: $" + couponAmount);
System.out.println("Grand total: $" + (finaltotal-couponAmount));
}
}
Thanks!
EDIT:
Would this work?
public void getLargest(){
for(Item currentProduct : shoppingBag){
System.out.println(Collections.max());
}
}
You probably want Collections.max() (and Collections.min(), respectively). If you want the entire list in order, you probably want Collections.sort().
Using Google Guava:
Function<Item, Double> itemCostFunction = new Function<Item, Double>() {
#Override public Double apply(Item item) {
return item.getCost();
}
};
List<Item> sortedItems = Ordering.natural().onResultOf(itemCostFunction).sortedCopy(shoppingBag);
Now
Item biggest = Iterables.getLast(sortedItems); // costliest
Item smallest = sortedItems.get(0); // cheapest
What do you want to sort on? Cost?
You can create an new class; CostComparator implementing a Comparator<Item>, and compare Items depeding on their price.