Please Help me to solve the Simple Java program - java

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

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

Is this the correct syntax for inputing a string to an if statement or am i completely off?

package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.

Method calculations/arguments in Java

I have to create a virtual coffee shop where the user enters their order number, how many of that order they want, calculate the subtotal and the discount, etc. The whole point of this is that the process's divided into various methods. Most of the methods are pretty simple, but I'm having trouble with the computeSubTotal method. I have to initialize subtotal in the main method to make this work, but when the subtotal's calculated in computeSubTotal, it always ends up being zero. Sorry if this seems stupid, but I have no idea what I'm doing wrong, help?
import java.util.Scanner;
public class CoffeeShopWithMethods
{
public static void main(String[] args)
{
Scanner user_input = new Scanner (System.in);
String user_name;
System.out.print("\nPlease enter your name: ");
user_name = user_input.next();
System.out.println("\nWelcome to the Java Byte Code Coffee Shop, " + user_name + "!");
int orderNumber = 0;
int orderQuan = 0;
double subTotal = 0.0;
//Beginning of calls to methods
displayMenu();
getItemNumber(orderNumber);
getQuantity(orderQuan);
computeSubTotal(orderNumber, orderQuan, subTotal);
discountCheck(subTotal);
}
public static void displayMenu()
{
System.out.println("\nHere is our menu: \n" + "\n 1. Coffee $1.50" + "\n 2. Latte $3.50" + "\n 3. Cappuccino $3.25" + "\n 4. Espresso $2.00");
}
public static int getItemNumber(int orderNumber) //prompts user for item number (1 for coffee, 2 for latte, etc...)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the item number: ");
orderNumber = user_input.nextInt();
final double Coffee = 1.50;
final double Latte = 3.50;
final double Cappuccino = 3.25;
final double Espresso = 2.00;
double Cost = 0;
if (orderNumber == 1)
Cost = Coffee;
if (orderNumber == 2)
Cost = Latte;
if (orderNumber == 3)
Cost = Cappuccino;
if (orderNumber == 4)
Cost = Espresso;
return orderNumber;
}
public static int getQuantity(int orderQuan)
{
Scanner user_input = new Scanner(System.in);
System.out.print("\nPlease enter the quantity: ");
orderQuan = user_input.nextInt();
return orderQuan;
}
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
public static boolean discountCheck(double subTotal) //takes subtotal and returns true if user earned a discount (over $10)
{
if (subTotal >= 10.00)
return true;
else
return false;
}
}
Your methods getItemNumber, getQuantity, computeSubTotal and discountCheck all return a value, but you are not storing that return value in your main method.
In addition to that, your getItemNumber() method is only storing the cost locally, which is then discarded when the method is finished - the cost should be returned (and the method probably renamed).
You probably should have something like this:
//Beginning of calls to methods
displayMenu();
double itemCost = getItemCost(); // was getItemNumber()
orderQuan = getQuantity(orderQuan);
subTotal = computeSubTotal(itemCost, orderQuan);
boolean shouldDiscount = discountCheck(subTotal);
Of course, to use an object-oriented approach, the variables should be members of your class, then you wouldn't need to pass or return values - they would be accessible to all methods in the class.
public static double computeSubTotal(int orderNumber, int orderQuan, double subTotal)
{
subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
In your computeSubTotal method, you do
subTotal = (orderNumber * orderQuan);
This is not going to intiailize the variable in the main method; you are re-initializing the parameter variable.
In your main method, you should be doing
subTotal = computeSubTotal(orderNum, orderQuan);
instead of calling the method without using the return value. You might have noticed that I didn't pass subTotal to the method. This is not needed. You can instead re-declare the variable inside the method:
public static double computeSubTotal(int orderNumber, int orderQuan)
{
double subTotal = (orderNumber * orderQuan);
System.out.print("Your total before discount and tax is: $" + subTotal);
return subTotal;
}
This applies to the other variables aswell. Java is pass-by-value, so if you pass a value to a method, a new reference is created for the method (when you do int varName in your method's parameters when you declare the method)

Local variable can't take methods parameters

I am new To Java please help me, my local variable can't take me methods parameters.
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.text.DecimalFormat; //I can not get my local variables in my
// main to accept my methods parameters.
// This is my program.
public class AccountBank
{
public static void main (String[] args) throws IOException
{
// Calling in my Class
Accountclass BankAcc = new Accountclass();
// initialize both there variables in. order to use them in a for loop.
double depDrw = 0;// this are one of the variables that is giving me problems
double withDrw = 0; // this is the other that is giving me problems
double totalW = 0;
double totalD = 0;
// declaring all my variables
String name="";
double month;
double startBal;
// This section will greet and accept input by asking the user to enter the starting alance and set it in my class
// Greetings
JOptionPane.showMessageDialog(null,"Lets Get Started");
// receiving input for my name variable
name = JOptionPane.showInputDialog(null, "Please Enter Your Name Below: ");
// ask user for starting balance
startBal = Double.parseDouble(JOptionPane.showInputDialog("What Is The Starting Balance In Your Account:"));
// This will set the value in my class
BankAcc.setBal(startBal);
// ask user how many months has the account been active
month = Double.parseDouble(JOptionPane.showInputDialog("Months That Account Has Been Active:"));
// This section will accept input by asking the user to enter each amount deposited every month from the account set it in my class.
// This will be shown in the message box
depDrw = depositTotal(deposit); << // I am having trouble here it wont take my parameters variable which I created on the buttom. please help
// This will sum up every amount the user enters in the message box.
totalD += depDrw;
// This will set the value in my class
BankAcc.setdeposit(totalD);
// This section will accept input by asking the user to enter each amount withdrawn every month from the account and set it in my class
// This will be shown in the message box
withDrw = withdrawTotal(wit); // <<< I am having problem here this variable does not take the value of my methods parameter, which i created on the bottom of this page.
// This will sum up every amount the user enters in the message box.
totalW += withDrw;
// This will set the value in my class
BankAcc.setwithdraws(totalW);
//This section will display the " monthly interest rate, monthly interest earned, total amount deposited, total amount withdrawn, and the final balance of the account."
DecimalFormat formatter = new DecimalFormat("#0.0000");
DecimalFormat formatter2 = new DecimalFormat("#0.0");
DecimalFormat formatter3 = new DecimalFormat("#0.00");
//Get the calculations from the savings account class and display them.
JOptionPane.showMessageDialog(null," Account Name: " +name+"\n \n Your Monthly Interest Rate Is ..... "
+ formatter.format(BankAcc.monthInt())+"%" + "\n \n Your Monthly Interest Earned Was ..... $"
+ formatter2.format(BankAcc.GetInt()) + "\n \n Your Overall Amount With Deposited Was ..... $" + totalD +
" \n \n Your Overall Amount WithDrawn Was ..... $" + totalW + " \n \n Your Remaining Balance Is ..... $"
+ formatter3.format(BankAcc.getFinalbal()),"Results", JOptionPane.PLAIN_MESSAGE );
}
public static double depositTotal( String deposit)
throws IOException
{
double sales;
double totalDeposit = 0;
File file = new File ("deposits.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
inputfile.close();
return totalDeposit;
}
public static double withdrawTotal( String wit)
throws IOException
{
double sales;
double totalwithdraws = 0;
File file = new File ("withdraws.txt");
Scanner inputfile = new Scanner(file);
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalwithdraws += sales;
}
inputfile.close();
return totalwithdraws;
}
Your while loop is
while (inputfile.hasNextDouble());
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
There shouldn't be a ; after the while (inputfile.hasNextDouble())
while (inputfile.hasNextDouble())
{
sales = inputfile.nextDouble();
totalDeposit += sales;
}
Similarly for other while loops, remove the ;
Change your method declaration so it doesn't receive any parameter. And because it's returning a double, you may store the value it returns in a double variable:
double deposit = depositTotal();
In your depositTotal() method:
public static double depositTotal() throws IOException {
...
}

Categories