My program must ask the quantity of batteries and display the quantity on the message pain. To do so I must pass the variable quantity = getQuantity so that I can display the number of batteries selected. The problem is when I do so it asks for user input "How many batteries would you like to purchase" twice. I am learning and a student so please provide help that provides better understanding. I don't simply want to fix the code I want to understand. I have played with just adding quantity and several other options but nothing seems to both display quantity of batteries selected and only ask the question once.
import javax.swing.JOptionPane;
import java.io.*;
/**
* #author Arnie
*/
public class VapeSolutions2 {
/**
* #param args
*/
public static void main(String[] args) {
// declare variables
String openingMsg, nameInputMsg, customerName, nameOutputMsg,
returnInputMsg, customerReturn, returnOutputMsg,
greetingOutputMsg, outputMsg, colorSelection, colorInputMsg, ColorOutputMsg, priceOutputMsg,
batteryOutputMsg;
int quantity;
double grandTotal;
// display opening message
openingMsg = "*** Welcome to Vape Ordering Solutions ***\n"
+ " It's a great day to order a Vape Supplies!";
JOptionPane.showMessageDialog(null, openingMsg);
// get required input using dialogs
nameInputMsg = "Please enter your name: ";
customerName = getStringInput(nameInputMsg);
returnInputMsg = "Are you a returning customer (yes or no)? ";
customerReturn = getStringInput(returnInputMsg);
colorInputMsg = "What Color would you like?";
colorSelection = getStringInput(colorInputMsg);
grandTotal = totalCost();
quantity = getQuantity();
// build output strings
nameOutputMsg = "Welcome " + customerName + ".\n\n";
returnOutputMsg = "Your return customer status is " + customerReturn + ".\n";
greetingOutputMsg = "Thank you for ordering from Vape Ordering Solutions!" + "\n\n"
+ "Your order will be shipped the following day" + ".\n";
ColorOutputMsg = "Your Color selected is " + colorSelection + ".\n";
batteryOutputMsg = "Total Batteries Ordered is" + quantity + ".\n";
priceOutputMsg = "Your total purchase price is $" + grandTotal + "\n";
// create and display output string
outputMsg = nameOutputMsg + returnOutputMsg + greetingOutputMsg + ColorOutputMsg + batteryOutputMsg
+ priceOutputMsg;
JOptionPane.showMessageDialog(null, outputMsg);
System.exit(0);
} // end main()
private static String getStringInput(String prompt) {
String input;
input= JOptionPane.showInputDialog(prompt);
int i = 0;
while (input.length() == 0 && i < 3){
JOptionPane.showInputDialog("Please enter a valid value\n"+ prompt);
i++;
if (i == 3){
JOptionPane.showMessageDialog(null,"You have exceeded the maximum attempts to input correct data");
System.exit(0);
}
}
return input;
}
private static int getQuantity( ){
int quantity;
String quantityMsg = "How many batteries would you like to order?";
String quant = getStringInput (quantityMsg);
quantity = Integer.parseInt(quant);
return quantity;
}
// total = grandTotal (quantity, 5,.07)
private static double totalCost( ) {
int number;
double cost, salesTaxRate, tax, grandTotal, subTotal;
cost = (20.00);
number = getQuantity ();
salesTaxRate = (.07);
subTotal = number * cost;
tax = subTotal * salesTaxRate;
grandTotal = subTotal + tax;
return grandTotal;
}
} // end class VapeSolutions2
try with:
quantity = getQuantity();
grandTotal = totalCost(quantity);
and update your method "totalCost":
// total = grandTotal (quantity, 5,.07)
private static double totalCost( int quantity) {
//code ...
number = quantity;
//code ...
}
Related
so for my assignment I have to create an input file consisting of a grocery order, then create an output file that prints the input file into a table with columns. While also calculating the total price of each item by multiplying the quantity by the unit price, then adding up all the total prices together. My problem is that I'm stuck on how im suppose to make a formatted table that evenly distributes the data from the input file. As well as how im suppose to incorporate the multiple mixed datas for my while loop.
I tried using hasnext(), followed by nextline(),nextInt(), and nextdouble() to read my data but had no success. Here's my code for reference.
import java.util.Scanner;
import java.io.*;
public class Assignment4 {
public static void main(String[] args) throws Exception {
PrintWriter input = new PrintWriter("groceryorder.txt");`
String food = "Oranges";
input.println(food);
int quantity = 30;
input.println(quantity);
double unitprice = 1.47;
input.println(unitprice);
food = "Cheese Block";
input.println(food);
quantity = 5;
input.println(quantity);
unitprice = 3.25;
input.println(unitprice);
food = "Crackers";
input.println(food);
quantity = 1;
input.println(quantity);
unitprice = 5.25;
input.println(unitprice);
food = "Grapes";
input.println(food);
quantity = 1;
input.println(quantity);
unitprice = 4.35;
input.println(unitprice);
food ="Onions";
input.println(food);
quantity = 10;
input.println(quantity);
unitprice = 1.25;
input.println(unitprice);
food = "Oatmeal";
input.println(food);
quantity = 2;
input.println(quantity);
unitprice = 5.67;
input.println(unitprice);
input.close();
File infile = new File("groceryorder.txt");
Scanner scanfile = new Scanner(infile);
PrintWriter output = new PrintWriter("groceryoutput.txt");
System.out.print("Item " + " Quantity " + " Unit Price" + "Total Price");
output.print("Item " + " Quantity " + " Unit Price" + "Total Price");
while (scanfile.hasNext()){
food = scanfile.nextLine();
quantity = scanfile.nextInt();
unitprice = scanfile.nextDouble();
double totalprice = (quantity * unitprice);
totalprice = scanfile.nextDouble();
}
output.print(food + quantity + unitprice + totalprice);
output.close();
}
}
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());
}
I haven't been able to make this code executable for class and can't find the reason why there are no errors prompting however when i execute i get this:
Exception in thread "main" java.lang.UnsupportedOperationException: Not
supported yet.
at set.fixedSalary(set.java:14)
at Main.main(Main.java:23)
C:\Users\the_h\AppData\Local\NetBeans\Cache\8.2\executor-
snippets\run.xml:53: Java returned: 1
I honestly have no idea how to fix this problem any help is appreciated I have the source code below.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private double fixedSalary;
private double commission;
private double salesTarget;
private double Acc_Rate;
private ArrayList<Double> annualSales;
private ArrayList name;
public static void main(String[] args){
// salesperson will earn a fixed salary of $32,600
set.fixedSalary(32600);
// The current sales target for every salesperson is $120,000.00
set.SalesTarget(120000.00);
//The acceleration factor is 2.1
set.Acc_Rate(2.1);
}
public ArrayList<Double> getAnnualSales(){
return annualSales;
}
public Main() {
this.name = new ArrayList();
this.annualSales = new ArrayList<>();
}
private float calculateCommission(double personSale) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
function read user input
class readData{
public void readData(){
// Creates a scanner object for sales entry.
Scanner input = new Scanner(System.in);
// prompts user for name of sales person
System.out.println("Please enter First Sales Person name: ");
name = addinput.nextLine();
// prompts user for name of sales person
System.out.println("Please enter 2nd Sales Person name: ");
name = addinput.nextLine();
//Prompts user for sales
System.out.println("Please enter annual sales First Person: ");
annualSales = addinput.nextDouble();
//Prompts user for sales
System.out.println("Please enter annual sales Second Person: ");
annualSales = addinput.nextDouble();
}
}
class calculateCommission {
double commission = 0.00;
double Acc_Rate;
calculateCommission() {
}
public double calculateCommission(double annualSales, double fixedSalary,
double salesTarget) {
this.Acc_Rate = 0.045 * annualSales;
double earnings = fixedSalary;
// The current commission is 4.5 of total sales
if(annualSales < 0.8 * salesTarget) {
earnings = fixedSalary + commission;
} else if (annualSales <= salesTarget){
//The current acc rate is 2.1 of total sales
commission = 0.045 * annualSales;
earnings = fixedSalary + commission;
} else if (annualSales > salesTarget){
earnings = fixedSalary + Acc_Rate;
}
return earnings;
}
} // function get commision
public double getCommission() {
return commission;
}
// function get total annual compensation
public double getTotalCommissionCalc(){
return fixedSalary + getCommission();
}
// funtion set value for fixedSalary
public void setfixedSalary(double fixedSalary){
this.fixedSalary = fixedSalary;
}
// funtion set value for salesTarget
public void setSalesTarget(double salesTarget){
this.salesTarget = salesTarget;
}
// funtion set value for incentive rate
public void setAcc_Rate(double Acc_Rate) {
this.Acc_Rate = Acc_Rate;
}
// Display a table of potential total annual compensation
public void displayResult(){
double annualSalesCalc;
double personSale;
for (int i = 0; i < name.size(); i++){
String personName = (String) name.get(i);
personSale = annualSales.get(i);
System.out.println("Total Compensation of Sales Person " +
personName + " is " + Math.round(calculateCommission(personSale)));
//Print column names
System.out.print("SalePerson\tTotal Sales\tTotal Compensation");
annualSalesCalc = personSale * 1.50;
while(personSale <= annualSalesCalc){
calculateCommission(personSale);
System.out.println((personName) + "\t\t" +
Math.round((personSale)) + "\t\t" +
Math.round(calculateCommission(personSale)));
personSale = personSale + 5000;
}
System.out.println(); // print blank line
}
if (annualSales.get(0) > annualSales.get(1)) {
System.out.println("Salesperson " + name.get(1)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(0)) + " is");
System.out.print("$" + Math.round((annualSales.get(0) -
annualSales.get(1))));
} else if(annualSales.get(1) > annualSales.get(0)){
System.out.println("Salesperson " + name.get(0)
+ "'s additional amount of sales that he must "
+ "achieve to match or exceed the higher of the salesperson
"
+ Math.round(annualSales.get(1)) + " is");
System.out.print("$" + Math.round((annualSales.get(1) -
annualSales.get(0))));
} else{
System.out.print("Both have same compensation");
}
}
}
It might be because your set.fixedSalary needs to be an integer because you dont set it as a double. you set it to 36000 when it needs to be 36000.0
I am in a Java class and I have a sales program as a project. My code will run but will not accept a second user's name as necessary in the code. It then makes a comparison between the two salaries. But my second calculation is not working correctly. Here is what I have:
package sales2;
import java.util.Scanner;
public class Sales2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Initialise scanner
String[] empName;
empName = new String[2];
double[] annualSales;
annualSales = new double[2];
System.out.printf("Please enter the employees name:"); // Question and input
empName[0] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary1 = Utils2.calculateSalary(annualSales[0]); // Read sales from input & calculate salary
System.out.println(empName[0] + "'s total yearly salary is: " + Utils2.numFormat(salary1)); // Print information for user
input.nextLine();
System.out.printf("Please enter the employees name:");
empName[1] = input.nextLine();
System.out.printf("Please enter your annual sales:");
annualSales[0] = Double.parseDouble(input.nextLine());
double salary2 = Utils2.calculateSalary(annualSales[1]); // Read sales from input & calculate salary
System.out.println(empName[1] + "'s total yearly salary is: " + Utils2.numFormat(salary2)); // Print information for user
if (salary1 > salary2){
System.out.println(empName[0] + " has a higher total annual compensation.");
System.out.println(empName[1] + " will need to increase their sales to match or exceed "
+ empName[0] + ", here is how much :" + (salary1 - salary2) );
}else if (salary1 < salary2){
System.out.println(empName[1] + " has a higher total annual compensation.");
System.out.println(empName[0] + " will need to increase their sales to match or exceed "
+ empName[1] + ", here is how much :" + (salary2 - salary1) );
}else {
System.out.println("\nBoth Salespersons have equal total annual compensation.");
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sales2;
/**
*
* #author etw11
*/
import java.text.DecimalFormat;
public class Utils2 {
public final static double FIXED_SALARY = 30000;
/**
* #param dec
* #return
*/
public static String numFormat(double dec) {
return new DecimalFormat("##,##0.00").format(dec);
}
/**
* Calculates the salary based on the given sales.
* #param sales The annual sales
* #return The calculated salary.
*/
public static double calculateSalary(double sales) {
double commissionRate = 0.10d;
if (sales < 320000) {
commissionRate = 0.00d;
} else if (sales >= 320000 && sales < 400000) {
commissionRate = 0.08d;
}
// System.out.println("The current commission is " + (int)
(commissionRate * 100) + "% of total sales.");
return FIXED_SALARY + (sales * commissionRate);
}
}
change this:
double annualSales = input.nextDouble();
to this:
double annualSales = Double.parseDouble(input.nextLine());
Found my issue. In this line:
annualSales[0] = Double.parseDouble(input.nextLine());
It should be:
annualSales[1] = Double.parseDouble(input.nextLine());
I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}