Im trying to insert the total_cost variable into the string in the last few lines without doing the ("its" + total_cost) method. Im trying to replicate the python {total_variable} method in java basically
import java.util.Scanner;
public class Decision2 {
public static void main(String[] arrgs) {
Scanner input = new Scanner(System.in);
int ticket = 0;
double total_cost = 0;
System.out.println("How many tickets do you want to buy?");
ticket = input.nextInt();
if (ticket >= 5) {
total_cost = total_cost + (10.95 * ticket);
} else {
total_cost = total_cost + (8.95 * ticket);
}
System.out.printf("The total cost is {total_cost}");
}
}
You can use java String Format
such as
String foo = String.format("The total cost is %.2f",total_cost);
or if printing use such as
System.out.printf("The total cost is %.2f\n",total_cost);
Related
I wanted to write a program that records bar inventory as I'm a bartender. I can't figure out how to pass the liquorCost and liquorCount data to the GetCostTotal() method below the main() method. I'm absolutely sure it's something fairly straightforward that I'm doing incorrectly but I just can't figure it out. Any help is appreciated.
My Liquor class is separate and I can post that if necessary but I don't think it's the class that's giving me the problem, it's retrieving the data input from the array to the separate method.
package inventory;
import java.util.Scanner;
public class Inventory {
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (liquorCost * liquorCount);
}
return costTotal;
}
}
try this
public static void main(String[] args) {
System.out.println("How many bottles are you taking inventory of?: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
Liquor[] inv = new Liquor[size];
for (int i = 0; i < inv.length; i++) {
inv[i] = new Liquor();
System.out.println("Enter product name: ");
inv[i].setLiquorName(keyboard.next());
System.out.println("Enter the count for the product: ");
inv[i].setLiquorCount(keyboard.nextDouble());
System.out.println("Enter the cost for the product: ");
inv[i].setLiquorCost(keyboard.nextDouble());
}
System.out.println("The sitting inventory cost of these products is: ");
//double totalCost = 0
for (Liquor inv1 : inv) {
System.out.println(inv1.getLiquorName() + ": $" + inv1.getLiquorCost() * inv1.getLiquorCount());
}
double costTotal = GetCostTotal(inv);
System.out.println("The total cost of the inventory is: "
+ costTotal);
System.exit(0);
}
public static double GetCostTotal(Liquor[] inv) {
double costTotal = 0;
for ( int i = 0; i < inv.length; i++) {
costTotal += (inv[i].getLiquorCost() * inv[i].getLiquorCount());
}
return costTotal;
}
Lets understand what went wrong here.Take a look at how you are trying to call the GetCostTotal() method.
double costTotal = GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount);
This is incorrect. The syntax/way you are calling the method is actually used when we what to define a method. Like you did:
public static double GetCostTotal(Liquor[] inv, double liquorCost, double liquorCount) {}
Your call should be like:
double costTotal = GetCostTotal(inv);
Here, we are passing only inv because the data for liquorCost and liquorCount is available inside "each" element of array inv.
Now you can accept this argument in GetCostTotal method. Here as you are iterating using a for loop, you can read the data you needed as inv[i].getLiquorCost() and inv[i].getLiquorCount().
I suggest you can read more on defining a method and calling a method in java.
I need to write a program that will allow the user to type in the name of an item followed
by a space and then the cost of the item. The user must continually type in item
names and costs. The program will terminate when the user enters "STOP" as input.
The program must determine the total cost of all the items entered.
Sample Input:
coke 12.50
pie 11.65
fanta 12.00
coffee 13.78
STOP
Sample Output:
Total Cost: R49.93
import java.util.Scanner;
import javax.swing.JOptionPane;
String details = "";
double total_cost = 0;
while(!details.equals("STOP")){
details = JOptionPane.showInputDialog("Enter item cost and name");
Scanner sc = new Scanner(details);
while(sc.hasNextDouble()){
double price = sc.nextDouble();
total_cost = total_cost + price;
System.out.println("Total Cost: R" + total_cost);
However my code outputs nothing except a build successful`enter code here. What am I doing wrong? Excuse the lack of polish in my question I am new to Stack Overflow.
You have to match STOP with the next token from the input, not with the whole of input. Also, as per your requirement, the input should be outside the loop. Do it as follows:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String details = JOptionPane.showInputDialog("Enter item cost and name");
Scanner sc = new Scanner(details);
double total_cost = 0;
while (sc.hasNext() && !sc.next().equalsIgnoreCase("STOP")) {
if (sc.hasNextDouble()) {
double price = sc.nextDouble();
total_cost = total_cost + price;
}
}
System.out.println("Total Cost: R" + total_cost);
}
}
Output:
Total Cost: R49.93
[Update]
If you want to process individual entries e.g. coke 12.50 and then pie 11.65 and so on, you can do it as follows:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
double total_cost = 0;
String details;
do {
details = JOptionPane.showInputDialog("Enter item cost and name");
String[] tokens = details.split("\\s+");
if (tokens.length >= 2) {
try {
double price = Double.parseDouble(tokens[1]);
total_cost = total_cost + price;
} catch (IllegalArgumentException e) {
System.out.println("Wrong input");
}
}
} while (!details.equalsIgnoreCase("STOP"));
System.out.println("Total Cost: R" + total_cost);
}
}
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;
}
This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 7 years ago.
Is there anyone who could guide me in the right direction on how to create an array of these employees? The array is set to a constant SIZE=10; Here is the my employee class and the driver with the array I tried. Also, I am aware that most of the output will be blank (employee name, id, etc) As I already know how to write it but so far have not. Also the "1" in class name "Employee 1" is only there because I already had another file saved under employee. Very new to java as you can most likely tell. Thank you
class Employee1{
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
my driver class:
import java.util.Scanner;
public class EmployeeDriver{
public static void main(String args[]){
// Invoking methods for each object created
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
//array that does not work //
Employee1 emp = new Employee1();
emp[0] = new Employee ();
/* invoke weeklyPay() method */
grossPayf= emp.weeklyPay(hoursWorkedf,hourlyRatef);
// invoke printEmployee() method
System.out.println (emp.toString());
}
}
What you are doing is creating a single object, not an array. An array would look like this:
final int SIZE = 10;
Employee1[] emp = new Employee1[SIZE];
Then each member of the array would have to be instantiated like this:
emp[0] = new Employee1();
public static final int SIZE = 10;
public static void main(String[] args) {
Employee1[] employees = new Employee1[SIZE];
}
As per Java doc:
An array is a container object that holds a fixed number of values of a single type.
In your case you are instantiating an object (Employee1 emp) and setting it at index 0. What about other indexes? You nee to run a loop and ask user for new employee and insert it at proper index ( 0-> 1 ->2 and so on).
Also your constructor accepts name of employee which you should also provide and print it in toString method. I have made some changes and the final code looks like:
public class Employee1 {
//variables
private String name;
private double grossPay;
// This is the constructor of the class Employee
public Employee1(String EmpName)
{
name = EmpName;
}
//calculates gross pay and returns
public double weeklyPay(double hoursWorked, double hourlyRate)
{
double timeAndHalf = (hourlyRate/2.0)+hourlyRate;
double dblOvtHours;
double dblOvtPay;
double regHours;
double ovtHours;
if (hoursWorked <= 40)
{
grossPay = hoursWorked*hourlyRate;
}
else if (hoursWorked > 40 && hoursWorked <= 60)
{
ovtHours = hoursWorked-40;
regHours = 40;
grossPay = (ovtHours*timeAndHalf) + (regHours*hourlyRate);
}
else if (hoursWorked > 60)
{
ovtHours = 20;
regHours = 40;
dblOvtHours = hoursWorked - 60;
dblOvtPay = hourlyRate * 2;
grossPay = (dblOvtPay*dblOvtHours) + (timeAndHalf * ovtHours)
+(regHours * hourlyRate);
}
return grossPay;
}/////////////////////////////////////////////////
/* Print the Employee details */
public String toString()
{
return "Employee Report\n" + "Name :" + name + "\nID number :"
+ "\nHours Worked" + "\nHourly Rate : " +"\nGross pay: " + grossPay ;
}
}
And the main is:
public static void main(String[] args) {
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("How many employees you want to enter: ");
final int empSize = input.nextInt();
Employee1[] employees = new Employee1[empSize];
for (int i = 0; i <empSize; i++) {
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
employees[0] = new Employee1("John");
grossPayf = employees[0].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[0].toString());
}
}
Note: I have done only minimum changes to make the program work. There are various other things you can improve in your code. The program runs as:
How many employees you want to enter:
2
Please enter the number of hours work: 11
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 112.75
Please enter the number of hours work: 10
Employee Report
Name :John
ID number :
Hours Worked
Hourly Rate :
Gross pay: 102.5
new code
public static void main(String[] args) {
final int SIZE=10;
final double hourlyRatef = 10.25;
double hoursWorkedf, wPay;
double grossPayf = 0.0;
String name = "Void";
Scanner input = new Scanner(System.in);
// System.out.println("How many employees you want to enter: ");
// final int empSize = input.nextInt();
Employee1[] employees = new Employee1[SIZE];
for (int i = 0; i <SIZE; i++)
{
System.out.print("Please enter the number of hours work: ");
hoursWorkedf = input.nextDouble();
System.out.print("Please enter employee name: ");
employees[i] = new Employee1(name);
grossPayf = employees[i].weeklyPay(hoursWorkedf,hourlyRatef);
System.out.println (employees[i].toString());
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)