I am creating a program that basically asks a user what they wish to purchase and gives them their total.
I am supposed to use 2 separate methods outside of Main to complete this task:
One method to get the user input as to which service they want performed, this method will also tell the user the total cost of the services (BEFORE TAX AND LABOR)
Another method to calculate labor costs and tax costs
The first method should return total cost to the main method, and the second method should get that total from the main method and calculate the Final Cost after labor and tax are added in.
(if the car is an import, 5% of the total should be added on)
Here is what I have so far:
import java.util.Scanner;
public class Assign3 {
public static double carMaintenance(String userCar) {
Scanner input = new Scanner(System.in);
String service_ordered="";
String more="yes";
double amount;
double total=0;
//declare and intialize parallel arrays, Services and Prices and display them to the user
String[] services = {"Oil Change" , "Tire Rotation", "Air Filter", "Fluid Check"}; //intialize list of services
double[]price = {39.99, 49.99, 19.99, 10.99}; //initialize corresponding price for services
for(int i= 0; i < services.length; i++) {
System.out.print( services[i]+ "...." );
System.out.print( price[i] + "\t");
}
do // *****2. THIS IS WHAT IS BEING EXECUTED FROM THE METHOD CALL IN MAIN *****
{
System.out.print("What service do you want done?: ");
String choice = input.nextLine();
if (choice.equalsIgnoreCase("oil change")) {
System.out.println("You chose an oil change");
amount = 39.99;
total = total + amount;
service_ordered+="Oil Change ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("tire rotation")) {
System.out.println("You chose a tire rotation");
amount = 49.99;
total = total + amount;
service_ordered+="Tire Rotation ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("air filter")) {
System.out.println("You chose an air filter");
amount = 19.99;
total = total + amount;
service_ordered+="Air Filter ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
} else if (choice.equalsIgnoreCase("fluid check")) {
System.out.println("You chose a flud check");
amount = 10.99;
total = total + amount;
service_ordered+="Fluid Check ";
System.out.print("Do you want to do another service? ");
more = input.nextLine();
}
} while (more.equalsIgnoreCase("yes"));
System.out.println("You ordered: " + service_ordered);
System.out.println("Your total due is " + total);
return total;
}
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.println("What kind of car do you have?: "); //****1. CODE STARTS HERE *****
String userCar = input.nextLine();
double total = carMaintenance(userCar); //*****2. CODE CALLS THIS METHOD AND EXECUTES IT *****
calcFinalPrice(total);
}
public static void calcFinalPrice(double total) {
double salesTax=.08;
double laborFee=.3;
double importFee=.05;
Scanner input = new Scanner(System.in);
System.out.println("Is your vehicle an import?: ");
String isImport = input.nextLine();
if(isImport.equals("yes")) {
total=total*laborFee+total; // this is the labor fee
double importTotal = total*importFee+total;
double totalAfterTax = importTotal*salesTax+importTotal; //this is the import total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle.");
}
if(isImport.equals("no")) {
total=total*laborFee+total; // this is the labor fee
double totalAfterTax = total*salesTax+total; //this is the total aftertax
System.out.println("It will cost " + totalAfterTax + " to fix your vehicle ");
}
}
}
Related
I did what i could and now the code works however when the user inputs the wrong value and is prompted to try again you have to hit enter and then you are asked to input a value, i cant think of what it is.
i also want to be able to get the program to start again after completing, i tried a do, while loop but it looped infinitely
public static void main(String[] args) {
String nameOfIngredient = null;
Float numberOfCups = null;
Float numberOfCaloriesPerCup = null;
Float totalCalories;
while(nameOfIngredient == null)
{nameOfIngredient = setIngredients(); }// Allows us to loop
while(numberOfCups == null)
{numberOfCups = setNumberOfCups(); }// Allows us too loop
while(numberOfCaloriesPerCup == null)
{numberOfCaloriesPerCup = setNumberOfCalories();} // Allows us to loop
totalCalories = numberOfCups * numberOfCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberOfCups + " cups and this amount contains " + totalCalories + " total calories.");
System.out.print("\n");
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static String setIngredients() {
System.out.println("Please enter the name of the ingredient: ");
Scanner scan = new Scanner(System.in);
try {
String ingredients = scan.nextLine();
System.out.println("\r");
return ingredients;
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCups() {
System.out.println("Please Enter Number Of Cups: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCups = scan.nextLine();
Float numberOfCupsFloat = Float.parseFloat(numberOfCups);
System.out.println("\n");
return numberOfCupsFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid Input must be a numeric value Please Try Again: ");
System.out.println("\n");
scan.nextLine();
}
catch (Exception e){
scan.nextLine();
System.out.println("Error taking in input, try again.");
}
return null;
}
//A method to be called on in the main class while loop making it easier to read and maintain
public static Float setNumberOfCalories() {
System.out.println("Please Enter Number Of Calories per cup: ");
Scanner scan = new Scanner(System.in);
try {
String numberOfCalories = scan.nextLine();
Float numberOfCaloriesFloat = Float.parseFloat(numberOfCalories);
System.out.println("\n");
return numberOfCaloriesFloat;
}
catch (NumberFormatException numberFormatException){
System.out.println("Invalid value Please enter a numeric value:");// if the input is incorrect the user gets prompted for the proper input
scan.nextLine();// if the input is incorrect the user gets prompted for the proper input
}
catch (Exception e){
scan.nextLine();
System.out.println("Error in input please try again.");
}
return null;
}
You may want to accept it as a string and check if it is numeric or not using String methods. Post that you can either move forward if format is correct or re prompt the user for correct value while showing the error.
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(!numCups.chars().allMatch( Character::isDigit ))
{
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
numberCups = Double.parseDouble(numCups);
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
Alternatively you could also do this using try catch statements. I believe this would be a better way to parse double values
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); //In case ingredient is more than one word long.
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
String numCups = scnr.next();
while(numberCups==0.0)
{
try {
numberCups = Double.parseDouble(numCups);
} catch (NumberFormatException e) {
System.out.println("Incorrect format for number of cups. Please enter numeric values");
numCups = scnr.next();
}
}
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
System.out.println(nameOfIngredient + " uses " + numberCups + " cups and this amount contains " + totalCalories + " total calories.");
}
I've taken your code and added support for input of fractional numbers. Comments added on important changes.
parseCups returns an Optional so we can tell if the input was valid or not.
parseIngredientValue does the work of deciding whether or not the input is a fraction and/or attempting to parse the input as a Double.
package SteppingStone;
import java.util.Optional;
import java.util.Scanner;
public class SteppingStone2_IngredientCalculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String nameOfIngredient = "";
String cupsStr = "";
double numberCups = 0.0;
int numberCaloriesPerCup = 0;
double totalCalories = 0.0;
System.out.println("Please Enter Ingredient Name: ");
nameOfIngredient = scnr.nextLine(); // In case ingredient is more than one word long.
Optional<Double> cups = Optional.empty();
while (cups.isEmpty()) { // repeat until we've got a value
System.out.println("Please enter the number of cups of " + nameOfIngredient + " required: ");
cupsStr = scnr.nextLine();
cups = parseCups(cupsStr);
}
numberCups = cups.get();
System.out.println("Please enter the number of calories per cup of " + nameOfIngredient + " : ");
numberCaloriesPerCup = scnr.nextInt();
totalCalories = numberCups * numberCaloriesPerCup;
// Using String.format to allow rounding to 2 decimal places (%2.2f)
System.out.println(String.format("%s uses %2.2f cups and this amount contains %2.2f total calories.",
nameOfIngredient, numberCups, totalCalories));
}
private static double parseIngredientValue(String input) {
if (input.contains("/")) { // it's a fraction, so do the division
String[] parts = input.trim().split("/");
double numerator = (double) Integer.parseInt(parts[0]);
double denomenator = (double) Integer.parseInt(parts[1]);
return numerator / denomenator;
} else { // it's not a fraction, just try to parse it as a double
return Double.parseDouble(input);
}
}
private static Optional<Double> parseCups(String cupsStr) {
double result = 0.0;
String input = cupsStr.trim();
String[] parts = input.split(" +"); // split on any space, so we can support "1 2/3" as an input value
switch (parts.length) {
case 2:
result += parseIngredientValue(parts[1]); // add the 2nd part if it's there note that there's no
// break here, it will always continue into the next case
case 1:
result += parseIngredientValue(parts[0]); // add the 1st part
break;
default:
System.out.println("Unable to parse " + cupsStr);
return Optional.empty();
}
return Optional.of(result);
}
}
Sample run:
Please Enter Ingredient Name:
Special Sauce
Please enter the number of cups of Special Sauce required:
2 2/3
Please enter the number of calories per cup of Special Sauce :
1500
Special Sauce uses 2.67 cups and this amount contains 4000.00 total calories.
We are required to complete a simple ticketing system for a local cinema in netbeans and I'm stumped on two problems.
Problem 1 is as part of the output, is once you have selected ticket type + quantity, there needs to be an output "you are purchasing X number of tickets at Y quantity"
Problem 2 is the seniors ticket needs to be at a cost of $32.50 and I cannot seem to find a workaround for allowing a calculation to be made using a decimal figure. I debugged and it seemed to change the number to an integer, which then would not calculate correctly. Help!
package ticketingsystem;
import java.io.*;
public class ticketingsystem
{
public static void main(String []args) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String order,again;
int quantity,price1=0,price2=0, price3=0,loop1=0,quantity1,quantity2=0;
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do{
System.out.println(" ");
System.out.print("Enter your option: ");
order=br.readLine();
if (order.equalsIgnoreCase("1")) {
price1=18;
} else if (order.equalsIgnoreCase("2")) {
price1=36;
}
else if (order.equalsIgnoreCase("3")) {
price1= (int) 32.5;
}
System.out.print("Enter the number of tickets: ");
quantity1= Integer.parseInt(br.readLine());
quantity2=quantity1+quantity2;
price2=price1*quantity2;
System.out.println("You are purchasing " int (order=br) " tickets at" (quantity1);
System.out.print("Do you wish to continue? (Y/N) : ");
again=br.readLine();
if (again.equalsIgnoreCase("y"))
loop1=loop1+1;
else loop1=loop1-100;
} while (loop1==1);
System.out.println(" ");
System.out.println("Total Price : "+price2);
}
}
Hi would suggest to make the following changes.
First rename price2 to totalPrice and change it to a double:
double totalPrice;
I would create an enum class for TicketType, where you can also assign the price1 value:
enum TicketType {
child(18), adult(36), senior(32.5);
TicketType(double price) {
this.price = price;
}
private double price;
public double getPrice() {
return price;
}
}
You can now change you main method to this:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String order, again;
int quantity = 0;
double totalPrice;
TicketType ticketType; // add the enum to the method
System.out.println(" ");
System.out.println("Welcome to the cinemas!");
System.out.println(" ");
System.out.println("MAIN MENU");
System.out.println(" ");
System.out.println("The cinema has the following options");
System.out.println(" ");
System.out.println("1 = Child (4-5 yrs)");
System.out.println("2 = Adult (18+ yrs)");
System.out.println("3 = Senior (60+ yrs)");
do {
System.out.println(" ");
System.out.print("Enter your option: ");
order = br.readLine();
//use a switch case instead of the if else pattern
switch (order.toLowerCase()) {
case "1":
ticketType = TicketType.child;
break;
case "3":
ticketType = TicketType.senior;
break;
default:
ticketType = TicketType.adult;
break;
}
System.out.print("Enter the number of tickets: ");
quantity = Integer.parseInt(br.readLine());
totalPrice += ticketType.getPrice() * quantity;
// %s will be replaced with the string value of ticketType, %.2f means it will be replaced with a decimal, round to decimals
System.out.printf("You are purchasing %s tickets at %.2f \n", ticketType, ticketType.getPrice());
System.out.print("Do you wish to continue? (Y/N) : ");
again = br.readLine();
}
while (again.equalsIgnoreCase("y"));
System.out.println(" ");
System.out.printf("Total Price : $%.2f \n", totalPrice);
}
You can use the System.out.printf() to format messages you print to the console
On the price1 value, you are losing some precision by storing it as an int.
In Java, the int is rounded (to floor) to values without the decimal point precision. For this purpose, you'll want to use float or double to retain your cent value.
Also, you may find the java.text.NumberFormat class useful for the Currency handling.
Have each department's number of computers stored in variables. Have the program store the values in variables, calculate the total and average computers and display them.
example output:
Chemistry: 4
Physics: 8
Music: 2
Math lab: 12
Total: 26
Average: 6.5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What is the name of your first class?");
String class1 = sc.nextLine();
System.out.print("What is the name of your second class?");
String class2 = sc.nextLine();
System.out.print("What is the name of your third class?");
String class3 = sc.nextLine();
System.out.print("What is the name of your fourth class?");
String class4 = sc.nextLine();
System.out.print(" \n\n");
System.out.println("How many computers are in each class?");
System.out.print(class1 + ": \t");
int class1comp = sc.nextInt();
System.out.print(class2 + ": \t");
int class2comp = sc.nextInt();
System.out.print(class3 + ": \t");
int class3comp = sc.nextInt();
System.out.print(class4 + ": \t");
int class4comp = sc.nextInt();
int sum = class1comp + class2comp + class3comp + class4comp;
double avg = sum / 4.0;
System.out.print(" \n\n");
System.out.println("\n\n" + class1 + ":\t" + class1comp);
System.out.println(class2 + ":\t" + class2comp);
System.out.println(class3 + ":\t" + class3comp);
System.out.println(class4 + ":\t" + class4comp);
System.out.println("\n");
System.out.println("Total:\t\t" + sum);
System.out.println("Average:\t" + avg);
}
}
After unit 2: Allow the user to add more departments.
I want the user to be able to add more classes until they say stop. Then later ask how many computers each class needs. Then display them, add them to the sum and average.
This should work for your purposes , it uses an ArrayList for the class names and an array of integers for the grades. It uses the AddOrdinal method taken from this answer.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> stringList = new ArrayList<>();
String capture;
int count =1;
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
count++;
stringList.add(capture);
System.out.println("Please enter your "+AddOrdinal(count) +" class:");
}
System.out.println("How many computers are in each class?");
int[] intList = new int[stringList.size()];
for (int i = 0; i < stringList.size(); i++) {
String className = stringList.get(i);
System.out.println(className + "\t:");
intList[i] = (scan.nextInt());
}
scan.close();
Arrays.stream(intList).sum();
int sum = Arrays.stream(intList).sum();
double average = (double)sum/intList.length;
/*
Output goes here
*/
}
I have to do this program where I have to display the calculation of the profit for each individual stock, but I also have to display the profit for the total amount of stocks. My code only has it so it displays the calculation for all of the stocks:
import java.util.Scanner;
public class KNW_MultipleStockSales
{
//This method will perform the calculations
public static double calculator(double numberShare, double purchasePrice,
double purchaseCommission, double salePrice,
double salesCommission)
{
double profit = (((numberShare * salePrice)-salesCommission) -
((numberShare * purchasePrice) + purchaseCommission));
return profit;
}
//This is where we ask the questions
public static void main(String[] args)
{
//Declare variables
Scanner scanner = new Scanner(System.in);
int stock;
double numberShare;
double purchasePrice;
double purchaseCommission;
double salePrice;
double saleCommission;
double profit;
double total = 0;
//Ask the questions
System.out.println("Enter the stocks you have: ");
stock = scanner.nextInt();
//For loop for the number stock they are in
for(int numberStocks=1; numberStocks<=stock; numberStocks++)
{
System.out.println("Enter the number of shares for stock " + numberStocks + ": ");
numberShare = scanner.nextDouble();
System.out.println("Enter the purchase price" + numberStocks + ": ");
purchasePrice = scanner.nextDouble();
System.out.println("Enter the purchase commissioned:" + numberStocks + ": ");
purchaseCommission = scanner.nextDouble();
System.out.println("Enter the sale price:" + numberStocks + ": ");
salePrice = scanner.nextDouble();
System.out.println("Enter the sales commissioned:" + numberStocks + ": ");
saleCommission = scanner.nextDouble();
profit = calculator(numberShare, purchasePrice, purchaseCommission,
salePrice, saleCommission);
total = total + profit;
}
//Return if the user made profit or loss
if(total<0)
{
System.out.printf("You made a loss of:$%.2f", total);
}
else if(total>0)
{
System.out.printf("You made a profit of:$%.2f", total);
}
else
{
System.out.println("You made no profit or loss.");
}
}
}
How can I get it so each individual stock profit gets shown, with the profit of all the stocks together?
Try maintaining a separate Map for profit/loss. You may want to accept Stock Name as an input which will help manage individual stocks effectively.
// Map of stock name and profit/loss
Map<String,Double> profitMap = new HashMap<String,Double>();
After calculating profit/loss, add entry to map
profitMap.put("stockName", profit);
total = total + profit;
At the end of your program, iterate and display profit/loss for each Stock from Map.
for (Entry<String, Integer> entry : profitMap.entrySet()) {
System.out.println("Stock Name : " + entry.getKey() + " Profit/loss" + entry.getValue());
}
what the program wants me to code:
Code an executable program that will produce
an invoice for a customer ordering a number
of products at a store. A sample run of the
program is shown to the right.
Your program
must ask for the number of products (up to a
maximum of 12 products may be ordered) and
then successively ask for the product name and
its cost. The invoice produced includes:
the title of the store (as shown),
product names and their cost,
calculated cost of all products,
calculated 5% sales tax,
overall total cost
a thank you.
The products and their cost must be kept in
parallel arrays. Two methods must be coded.
One method will display the title. The second
method will accept the calculated cost of all
products and return the calculated sales tax.
The method that computes the sales tax must
use a named constant for the 5% tax rate.
picture of example run of what it should look like: http://imgur.com/F3XDjau
Currently my program is this so far, but im not sure if it is correct or if i need to make the variables into an array.
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int product;
String products;
double cost;
System.out.println("How many products? ");
product=input.nextInt();
for(int i = 0; i < product; i++){
System.out.println("Product Name: ");
products=input.next();
System.out.println("Cost: ");
cost=input.nextDouble();
}
}
}
this is how you can fill your array:
double[] costArray = new double[product];
for(int i = 0; i < product; i++){
costArray[i] = input.nextDouble();
}
You need to use an array for variables products and cost like this:
static final float TAXES = 0.05f;
public static void main(String[] args) {
double sum = 0.0;
double tax;
Scanner input = new Scanner(System.in);
int product;
String products[];
double cost[];
System.out.println("How many products? ");
product = input.nextInt();
products = new String[product];
cost = new double[product];
for (int i = 0; i < product; i++) {
System.out.println("Product Name: ");
products[i] = input.next();
System.out.println("Cost: ");
cost[i] = Double.parseDouble(input.next().trim().replace(',', '.'));
}
indentedText();
for (int i = 0; i < product; i++) {
System.out.printf(products[i] + '\t' + "%.2f %n", cost[i]);
sum = sum + cost[i];
}
tax = calculateTaxes(sum);
System.out.printf("Sub total:" + '\t' + "%.2f %n", sum);
System.out.printf("Sales tax:" + '\t' + "%.2f %n", tax);
System.out.printf("Total to be paid:" + '\t' + "%.2f %n %n", (sum + tax));
System.out.print('\t' + "Thank you!");
}
private static void indentedText() {
System.out.print('\t' + "The Company Store" + '\n' + '\n');
}
private static double calculateTaxes(double sum) {
return sum * TAXES;
}