Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is my first time to use stack overflow to ask a question. I'm a beginner of Java programming. I was stuck on my assignment, can anyone help me to solve?
So, the problem is using java if-else to write the contents on the image into java code. But I didn't get the question. Can anyone explain? Is it possible to code using if-else? Thank you.
import java.util.Scanner;
public class MailOrderHouse{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double product1;
double product2;
double product3;
double product4;
double product5;
System.out.println("Product price: ");
double product_price = sc.nextDouble();
System.out.println("Enter quantity sold: ");
int quantity = sc.nextInt();
}
}
I totally don't understand the question.
First, indicate to User the products available and their respective price:
int productChoice = 0;
int quantity = 0;
double totalSum = 0.0;
System.out.println("Welcome To The Mail_Order House.");
System.out.println("Please select Product Number (1 to 5) you want to buy:\n");
System.out.println("1) Product Name 1: RM2.98");
System.out.println("2) Product Name 2: RM4.50");
System.out.println("3) Product Name 3: RM9.98");
System.out.println("4) Product Name 4: RM4.49");
System.out.println("5) Product Name 5: RM6.87");
This allows the User to easily see what is available to buy and therefore make a valid choice. Now ask the User to enter a product number:
productChoice = sc.nextInt();
The value the User supplies relates to the product name he/she wants. Now it's just a matter of asking the User the desired quantity of that specific product:
System.out.println("What quantity of Product #" + productChoice + " do you want?");
quantity = sc.nextInt();
Now that we have the product quantity it's a matter using IF/ELSE IF to gather the price of that selected product and multiply it by the User supplied quantity to achieve the total sum owed for that product:
if (productChoice == 1) {
// ......TO DO........
}
else if (productChoice == 2) {
totalSum += 4.50 * quantity;
// This is the same as: totalSum = totalSum + (4.50 * quantity);
}
else if (productChoice == 3) {
// ......TO DO........
}
else if (productChoice == 4) {
// ......TO DO........
}
else if (productChoice == 5) {
// ......TO DO........
}
else {
System.out.println("Invalid product number supplied!");
}
As you can see, you now have all the required data to display the required output String to Console:
System.out.println("Mail-Order House sold " + quantity +
" of Product #" + productChoice + " for: RM" +
String.format("%.2f", totalSum));
The String.format("%.2f", totalSum) in the above line ensures a precision of 2 decimal places in the total sum is displayed to console. You wouldn't want a number like: 21.422000522340 to be displayed as a monetary value in this particular case (read up on the String.format() method).
You have to take 5 inputs for number of products sold & 5 inputs for product prices. You have to calculate the total price of these products. Instead of taking 10 variables for 10 inputs you can just use a loop like:
import java.util.Scanner;
public class MailOrderHouse{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double total = 0;
int totalProduct = 0;
for (int i = 0; i < 5; i++) {
int productQuantity = sc.nextInt();
double productPrice = sc.nextDouble();
total += productPrice;
totalProduct += productQuantity;
}
System.out.println("Mail-order house sell " + totalProduct + " product " + totalProduct + " for RM" + productPrice);
}
}
Couldn't understand your input format though. Hope it helps.
Related
I need an instance in my program to work in that if the user inputs a payment number (payment) that is equal to the total price of a checkout with taxation (price3), the program will just list 0.00 as change and not repeat user input as if the user's payment is less than the price. However, when payment equals price3 (payment - price3 == 0), the program goes to the else-if statement. How do I fix this?
Example: price3 == 28, payment == 28, the output after payment input is "You still owe..." and so on instead of "Your change is $0.00".
I think it is skipping the first if-statement in the while loop, but I have no idea why. I already tried moving around the if-statements in the while-loop to no avail.
There are no error messages.
Note: I am still trying to learn Java. Just started recently.
The program code which my question references is displayed below:
import java.util.Scanner;
public class Checkout
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many items are you purchasing?");
int count = input.nextInt();
double price1 = 0;
double price2 = 0;
String userItem = "";
for(int i = 1; i<=count; i++)
{
System.out.println("Please enter the name of the item:");
input.nextLine();
userItem = input.nextLine();
System.out.println("Please enter the price of the item:");
price1 = input.nextDouble();
System.out.println();
System.out.printf("Your item #" + i + " is " + userItem + " with a price of $" + "%.2f", price1);
System.out.println();
price2 = price2 + price1;
}
System.out.println();
System.out.printf("Your total amount is: $" + "%.2f", price2);
double price3 = price2 + (price2 * 0.06);
System.out.println();
System.out.printf("Your total amount with tax is: $" + "%.2f", price3);
System.out.println();
System.out.println("I need a payment!");
double payment = input.nextDouble();
boolean condition = false;
while(condition == false)
{
if(payment - price3 == 0)
{
condition = true;
}
else if(payment < price3)
{
System.out.println();
System.out.printf("You still owe " + "%.2f", (price3-payment));
System.out.println();
System.out.println("I need a better payment!");
payment = input.nextDouble();
}
else
{
condition = true;
}
}
double change = payment - price3;
System.out.println();
System.out.printf("Your change is: $" + "%.2f", change);
}
}
The core of your problem lies in (1) expecting exact equality of floating-point value, and (2) displaying quantities to 2 decimal places.
Given the user is told the amount to pay (price3) using 2 places of decimals, even if he enters that exact same value as payment, it may not match the true value of price3.
Ideally you should do all calculation in pennies (or whatever the smaller unit of this currency is). Failing that, your criterion for having paid the right amount should be something like the difference between price and payment is less than 0.01.
In the stated case
Example: price3 == 28, payment == 28, the output after payment input
is "You still owe..." and so on instead of "Your change is $0.00".
if the price before tax is 26.415 it makes the price after tax 27.9999, which displays as 28.00 but is not equal to 28.00. Neither 26.41 nor 26.42 get you to an after-tax displayed price of 28.00.
that is happening because of price3=price2+(price2*0.06). So, when it is comparing payment with price3, it is always less. See below
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;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with my online lab, I'm given this code below and I can only modify the places where it says '// FIX ME'. I've already added the following answers in the blanks but I still don't have it quite right. I was thinking about writing another code on top asking for how many items I would like to input and then creating a DO Loop centered around that but this isn't what the question wants from me. It's possible that I'm just looking at this the wrong way, any help would be appreciated!
Here is the Lab;
The following program should input a list of items, including the description of the item, the number of items purchased and the unit price of the item; then calculate the total bill. The input of the list is complete when "Finish" is entered for the description. Complete the program so that it works correctly.
import java.util.Scanner;
public class CalculateBill {
public static void main( String[] args ) {
double sum = 0;
double cost;
int items;
double unitPrice;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name of the item (Finish to end):");
String description = scan.next();
while( items != 0 ) { // FIX-ME
System.out.println("Please enter the quantity of " + description + ": " );
items = scan.nextInt();
System.out.println("Please enter the unit price of " + description + ": ");
unitPrice = scan.nextDouble();
cost = Price++ ; // FIX-ME
System.out.printf("Cost of %d %s(s) is $%.2f%n", items, description, cost);
sum = sum+1; // FIX-ME
System.out.println("Please enter the name of the item (Finish to end):");
description = scan.next();
}
System.out.printf("The total bill is $%.2f%n" ??? ); // FIX-ME
}
}
This is what I did to get it working:
import java.util.Scanner;
public class CalculateBill {
public static void main( String[] args ) {
double sum = 0;
double cost = 0;
int items=0;
double unitPrice;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the name of the item (f to end):");
// changed to f as I don't want to have to type Finish every time
String description = scan.next();
while( !description.equals("f") ) { // FIXED
System.out.println("Please enter the quantity of " + description + ": " );
items = scan.nextInt();
System.out.println("Please enter the unit price of " + description + ": ");
unitPrice = scan.nextDouble();
cost = items*unitPrice ; // FIXED
System.out.printf("Cost of %d %s(s) is $%.2f%n", items, description, cost);
sum += cost; // FIXED
System.out.println("Please enter the name of the item (F to end):");
description = scan.next();
}
System.out.printf("The total bill is $%.2f%n", sum); // FIXED
}
}
I am working on an assignment for school and I have a basic program already that calculates the total cost of a trip by asking the total mileage, average mpg of car, and cost per gallon of gas. This works great but I also need to add a few more items and I am unsure of how to do so. First I need to include a menu of some sort giving the option to either calculate the trip cost or exit the program. Next I need to incorporate somewhere in the program a bit asking if the user wants an oil change or not and then based on the answer adding this to the total.
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}
}
As you can see I added a little bit asking if they want an oil change. My vision of doing it would be to create a variable for either the y or n answer and then an if else statement based on whether y or n. If y it will add 39.99 to a new variable "oil". If n it will make the variable 0. Oil has been incorporated into the final equation regardless of it's value for ease.
I am not looking for anyone to do my assignment for me. I guess I am looking to see what this would look like or if anyone has any input as far as how I should tackle this. Thank you for any help you can provide!
First I need to include a menu of some sort giving the option to
either calculate the trip cost or exit the program.
You can use a switch statement.
//ask for user to enter 0 to exit, 1 to calculate the trip
switch(answer) {
case 0 : System.exit(0);
break;
case 1 : //calculate cost trip here
break;
default : System.exit(0);
}
Next I need to incorporate somewhere in the program a bit asking if
the user wants an oil change or not and then based on the answer
adding this to the total
Well you can get the value of the user with your Scanner object like you did and write an if statement to check this value.
System.out.println("Would you like an oil change? Enter Y or N");
//here get the value of the user using your scanner object
double oil = 0;
if(/*test if value is equals to y*/)
oil += 39.99;
Hints :
to avoid testing if the value is "y" or "Y", use the method equalsIgnoreCase of the String class.
when this will works you can wrap the functionnality of calculating the trip cost in a method and call this method in the case 1 of the switch statement.
Edit
import java.util.Scanner;
public class GasCalculator {
public static void main (String args[])
{
double total = 0;
Scanner scan = new Scanner(System.in);
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
char oil = scan.next().charAt(0);
if (Character.toUpperCase(oil) == 'Y'){
System.out.println("Cost of oil change id 39.99);
System.out.println("39.99 will be added to your total cost");
total += 39.99;
}
double cost = (miles / mpg * gas);
total += cost;
String menu = "Pick a menu option: \n"
+ "1. Calculate total \n"
+ "2. exit";
System.out.println(menu);
int choice = scan.nextInt();
if (choice == 1){
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + total + "."));
} else {
System.exit(0);
}
}
}
You can implement exit option like this:
System.out.println("Choose your desired option:\n1)Calculate Trip Cost\n2)Exit");
int answer = scan.nextInt();
if (answer==1){
// the rest of your program
System.out.println("How many miles do you plan to travel?");
int miles = scan.nextInt();
System.out.println("So you will drive " + miles +" miles.");
System.out.println("What is the price of gas?");
double gas = scan.nextDouble();
System.out.println("Ok, so gas costs $" + gas +" per gallon.");
System.out.println("What is the average MPG of your car? Use the nearest whole number.");
int mpg = scan.nextInt();
System.out.println("So, you get " + mpg +" miles per gallon.");
System.out.println("Would you like an oil change? Enter Y or N");
double cost = (miles / mpg * gas + oil);
System.out.println("Below is your total cost");
System.out.println(String.format("Your trip will cost $" + cost + "."));
}
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);