Calculating Bill (Array and Do Loop for Java) [closed] - java

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
}
}

Related

Using java if-else [closed]

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.

Multiply all values together in string format printing in java [closed]

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 6 years ago.
Improve this question
I've only had a few hours practicing and learning Java so I'm still learning the basics.
I'm reading values from a text file, which contains:
Single
60
112.50
Master
70
2227.50
Penthouse
5
5000.00
(So it appears as when run)
Room Type: Single, Bookings: 60, Room Price: £112.00, Income: £6,750.00, Tax: 1350.00
And so fourth with each room.
I've printed all the values in a string format which is required. However, my problem is really simple.
I just want to add all the income together in a totalincome variable and add all the paidTax together in a totalpaidTax variable, then continue to print out it, to basically show the total tax paid and total income from all the rooms.
Although, I just don't know how to write it. I've had multiple attempts at trying but just no luck.
Here's my current code.
import java.io.FileReader;
import java.util.Scanner;
public class WagesCalculator {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
//Current tax variable value
double tax = 20;
//User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
//if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y")) {
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
//Prints out current tax value
System.out.println("The current tax rate is " + tax+".");
while (file.hasNext()) {
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
double income = numberOfBookings * price;
double paidTax = income*(tax/100);
//String format print out final calculations
System.out.printf("Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n", name, numberOfBookings, price, income, paidTax);
}
file.close();
}
}
Objects are your friend.
Create an object for each Room in your input.
Store the Rooms in a List.
Aggregate values from the List.
Print accordingly.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WagesCalculator
{
public static void main(String[] args)
throws Exception
{
WagesCalculator wc = new WagesCalculator();
wc.calculate();
}
public void calculate()
throws FileNotFoundException
{
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
// Current tax variable value
double tax = 20;
// User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
// if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y"))
{
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
// Prints out current tax value
System.out.println("The current tax rate is " + tax + ".");
List<Room> rooms = new ArrayList<Room>();
while (file.hasNext())
{
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
rooms.add(new Room(tax, name, numberOfBookings, price));
}
file.close();
rooms.stream().forEach(e -> System.out.println(e));
double totalIncome = rooms.stream().map(r -> r.income)
.reduce((a, b) -> a + b).orElse(0.0);
double totalTax = rooms.stream().map(r -> r.tax).reduce((a, b) -> a + b)
.orElse(0.0);
System.out.printf("Total income was: %d\nTotal tax was %d\n", totalIncome,
totalTax);
}
class Room
{
double tax;
String name;
int numberOfBookings;
double price;
double income;
double paidTax;
public Room(double tax, String name, int numberOfBookings, double price)
{
this.tax = tax;
this.name = name;
this.numberOfBookings = numberOfBookings;
this.price = price;
this.income = numberOfBookings * price;
this.paidTax = income * (tax / 100);
}
#Override
public String toString()
{
return String.format(
"Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n",
name, numberOfBookings, price, income, paidTax);
}
}
}

Main class java does not return the value i passed in using scanner [closed]

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 7 years ago.
Improve this question
I have this main class
public class Hotel
{
Scanner scan = new Scanner(System.in);
Register[] items = new Register[15];
int count = 0;
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register deluxe = new Deluxe();
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
run.enterItems();
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
}
public double calcTotal()
{
double total = 0;
for(int i = 0;i<count;i++)
{
total += items[i].total();
}
return total;
}
that is supposed to return the value i put in in the scanner here in the enterItems() that is in the class as the main class
public void enterItems()
{
int type, quantity, sale,night;
double price;
............................
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
}
So this will pass to the class called Deluxe where i have this method called displayInfo()
public class Deluxe implements Register
{
int quantity,night;
double sale;
public Deluxe(){}
....................................
public double total()
{
double total, price = 200.0;
price = price*quantity*night;
total = price - (price * (sale/100));
total += total *.06;
return total;
}
public void displayInfo(){
if (quantity > 0){
System.out.println("Room Type : Deluxe Room");
System.out.println("Quantity: " +quantity);
System.out.println("Discount: " +sale);
}
}
}
the problem is, in checking for quantity > 0, it actually does not get any value that i put in in the scanner. It will always return 0 for quantity regardless what amount i put in.
But the calculation works fine. Calculation is to calculate how many (quantity) rooms book x night stay x the room's price.
The calculation is also in the same class as the displayInfo() which is in class Deluxe.
So i was wondering what did i do wrong here.
The quantity which you input here:
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
Goes into main(String[] args).quantity that's defined here:
public class Hotel
{
....
public static void main(String[] args)
{
...
int quantity, sale,night;
...
}
The quantity that you check here:
if (quantity > 0){...}
Is a different parameter - it's Deluxe.quantity and is defined here:
public class Deluxe implements Register
{
int quantity,night;
...
}
Those two parameters have no relation. If you want them both to be the same, you need to pass to class Deluxe the main(String[] args).quantity parameter. You can do this via your own constructor under Hotel.main(String[] args), like so:
DecimalFormat fmt = new DecimalFormat("0.##");
Hotel run = new Hotel();
int quantity, sale,night;
Register family = new Family();
Register suite = new Suite();
Scanner input = new Scanner(System.in);
System.out.println("Enter customer's name:");
String name = input.next();
quantity = run.enterItems();
Register deluxe = new Deluxe(quantity,0,0); // entering the default value for the other two parameters like the empty constructor would leave them.
if(run.count != 0)
{
System.out.println("\nHotel Reservation Payment");
System.out.println("============================");
System.out.println("Customer name: " + name);
deluxe.displayInfo(); //supposed to print the details
family.displayInfo(); //supposed to print the details
suite.displayInfo(); //supposed to print the details
System.out.println("The final total is RM" + fmt.format(run.calcTotal()));
}
else
{
System.out.println("No items entered.");
run.enterItems();
}
if you change your enterItems() function to return the quantity parameter you need, like so:
public int enterItems()
{
int type, quantity, sale,night;
double price;
.........
System.out.println("\nNow please enter how many of Deluxe Room you want to book.");
quantity = scan.nextInt();
System.out.println("\nHow many night?");
night = scan.nextInt();
items[count] = new Deluxe(quantity,sale,night);
count++;
return quantity;
}
Notice, this solves this only for the quantity parameter. if you need more, you might need to return the Deluxe structure from enterItems(). Good luck!

My scanner skips over my next double and next integer? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 9 years ago.
Whenever I'm running my scanner it skips over the height(double) loop after weight. It also skips over the level(int) loop after age.
Here's my scanner class.
import java.util.Scanner;
public class HowHealthy
{
public static void main(String[] args)
{
String aGender = "";
//New healthy objec tis created
Healthy person = new Healthy();
//Scanner object is created
Scanner in = new Scanner(System.in);
String name = "";
while(!person.setName(name))
{
System.out.print("Person's name: ");
name = in.nextLine();
if(!person.setName(name))
{
System.out.println("Invalid name - must be at least one character!");
}
}
char gender = '\0';
while(!person.setGender(gender))
{
System.out.print(name + ", are you male of female (M/F): ");
gender = in.nextLine().toUpperCase().charAt(0);
if(!person.setGender(gender))
{
System.out.println("Invalid gender - must be M or F (upper or lower case)":
}
}
double weight = 0;
while(!person.setWeight(weight))
{
System.out.print(name + "'s weight (pounds): ");
weight = in.nextDouble();
in.nextLine();
if(!person.setWeight(weight))
{
System.out.println("Invalid weight - must be at least 100 pounds!");
}
}
double height = 0;
while(!person.setHeight(height))
{
System.out.print(name + "'s height (inches): ");
height = in.nextDouble();
if(!person.setHeight(height))
{
System.out.println("Invalid height - must be 60..84, inclusively!");
}
}
int age = 0;
while(!person.setAge(age))
{
System.out.print(name + "'s age (years): ");
age = in.nextInt();
in.nextLine();
if(!person.setAge(age))
{
System.out.println("Invalid age - must be at least 18!");
}
}
System.out.println();
System.out.println("Activity Level: Use these categories:");
System.out.println("\t1 - Sedentary (little or no exercise, desk job)");
System.out.println("\t2 - Lightly active (little exercise / sports 3-5 days/wk");
System.out.println("\t3 - Moderately active(moderate exercise / sports 3-5
System.out.println("\t4 - Very active (hard exercise / sports 6 -7 day/wk)");
System.out.println("\t5 - Extra active (hard daily exercise / sports \n\t physica2X)
int level = 0;
while(!person.setLevel(level))
{
System.out.print("How active are you? ");
level = in.nextInt();
if(!person.setLevel(level))
{
System.out.println("Invalid acitvity level - must be 1..5, inclusively!");
}
}
System.out.println();
//Creates a new Healthy object and prints values based on user's input
System.out.println(person.getName()+ "'s information");
System.out.printf("Weight: %.1f %s \n", person.getWeight(), "pounds");
System.out.printf("Height: %.1f %s \n", person.getHeight(), "inches");
System.out.println("Age: " + person.getAge() + " years");
if (gender == 'M')
{
aGender = "male";
}
else
{
aGender = "female";
}
System.out.println("These are for a " + aGender);
System.out.println();
//Calculates the person's BMR, BMI and TDEE based on user input
System.out.printf("BMR is %.2f \n", person.calcBMR());
System.out.printf("BMI is %.2f \n", person.calcBMI());
System.out.printf("TDEE is %.2f \n", person.calcTDEE());
//Determines person's weight status based on BMI calculated
double BMI = person.calcBMI();
//Displays person's weight status
System.out.println("Your BMI classifies you as " + person.calcWeightStatus());
}
}
Here is my scanner class.
In both cases, you're missing in.nextLine() after you do in.nextInt(). If all of the other lines of code are working using things like in.nextDouble() followed by in.nextLine() my guess is that's what's missing.
Since it is skipping over the loops completely, there is something wrong with your methods for setHeight() and setLevel().
while(!person.setHeight(height))
If it is skipping this loop, it must mean that setHeight(height) is returning true when it should be returning false, or you need to get rid of the '!'

Please Help me to solve the Simple Java program

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);

Categories