How would i program this correctly? - java

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

Related

Allow for a variable to affect number of statements in a loop

Is there any way to allow "testscore" variable to affect the number of statements in the do while loop? Like if say testscore = 4, I can have up to score4, and it will be included in the calculations.
import javax.swing.JOptionPane;
public class Task4 {
public static void main(String[] arges) {
double nof=1;
double testscore;
double score1;
double score2;
double score3;
double averagescore;
double x=11;
String input;
input=JOptionPane.showInputDialog("How many students do you have?");
nof = Double.parseDouble(input);
input=JOptionPane.showInputDialog("How many test scores per student?");
testscore=Double.parseDouble(input);
do {
input=JOptionPane.showInputDialog("Enter score 1");
score1= Double.parseDouble(input);
input=JOptionPane.showInputDialog("Enter score 2");
score2 = Double.parseDouble(input);
input=JOptionPane.showInputDialog("Enter score 3");
score3=Double.parseDouble(input);
averagescore = (score1 + score2 + score3)/testscore;
JOptionPane.showMessageDialog(null, "The student's average test score is " + averagescore);
x++;
} while (x <= nof);
}
}
Yes, you can use a for loop to gather the scores. If you're only using the scores to compute the average then you can just keep a running total. If you need the scores for more than that you can create a double[] scores = new double[testscores]; variable to store them in as they are read.
public static void main(String[] arges) {
int nof = 1; // this should be an int since you can't have a partial student
int testscore; // also an int since you can't have a partial test
String input;
input = JOptionPane.showInputDialog("How many students do you have?");
nof = Integer.parseInt(input);
input = JOptionPane.showInputDialog("How many test scores per student?");
testscore = Integer.parseInt(input);
for (int num = 1; num <= nof; num++) {
double total = 0;
for (int i = 0; i < testscore; i++) {
input = JOptionPane.showInputDialog("Student #" + num + ": Enter score " + i);
total += Double.parseDouble(input);
}
double averagescore = total / testscore;
JOptionPane.showMessageDialog(null, "Student " + num + "'s average test score is " + averagescore);
}
}

How to output each stock?

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

Java writing for loop with user input

/**I am trying to ask for user input for the number of the books they want to order, then using for find the cost of each book, total them up and give them their receipt at the end for their order. I understand how to give them the output just having trouble with my loop.*/
import java.util.Scanner;
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal, subtotal, taxPaid;
System.out.print("Please enter the number of books you're ordering: ");
double numberOfBooks = in.nextDouble();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;
}
double subtotal = numberOfBooks * priceOfBooks;
double taxpaid = subtotal * (TAX);
double shippingCharge = SHIPPING * numberOfBooks;
double sumOfOrder = bookSubtotal + priceOfOrder + shippingCharge + TAX;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + subtotal);
System.out.println("Tax: $" + taxPaid);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}
You seem to increment counter twice:
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal = priceOfBooks + bookSubtotal;
counter ++;//this line
}
What happens in this line is that you increment counter, but the loop does that for you, because of:
for(counter = 0;counter<numberOfBooks;counter++)
the counter++ in that line increments counter for you, so just remove the
counter++;
line in the for loop (the one I wrote this line next to)
Also, you should set a value to bookSubtotal:
int bookSubtotal = 0;
in the beginning.
Additionally, you might want to make numberOfBooks an integer:
int numberOfBooks = in.nextInt();
And you shouldn't re declare subtotal twice, just remove the word double in the line:
double subtotal = (double)numberOfBooks * priceOfBooks;
Nor do you need the create taxpaid before the loop, because you have taxPaid after it. Naming is case sensitive, meaning capital letters Are ImpOrtaNt...
public class BookOrder {
public static void main(String[] orgs){
Scanner in = new Scanner(System.in);
final double TAX = .065;
final double SHIPPING = 2.95;
int counter = 0;
double bookSubtotal = 0;
System.out.print("Please enter the number of books you're ordering: ");
int numberOfBooks = in.nextInt();
for (counter = 0; counter < numberOfBooks; counter++){
System.out.println("Please enter the cost of your book: ");
double priceOfBooks = in.nextDouble();
bookSubtotal += priceOfBooks;
}
double shippingCharge = SHIPPING * numberOfBooks;
double tax = TAX * bookSubtotal;
double sumOfOrder = bookSubtotal + shippingCharge + tax;
System.out.println("Number of books purchased:" + numberOfBooks);
System.out.println("Book subtotal: $" + bookSubtotal);
System.out.println("Tax: $" + tax);
System.out.println("Shipping: $" + shippingCharge);
System.out.println("-------------------------------");
System.out.println("The price of the order is $" + sumOfOrder + ".");
}
}

How to use arrays in this java code so I can output values in order they are assigned to positions ?

I am a java beginner and I am coding a program that gets the name of the item, units of that item, price/unit and the total price. I am trying to put those values in different arrays
so I can access them later when I create a sort of a receipt but I don't know how to assign those values in array positions and then access those same positions without having to hard-code. A loop is the best option but I dont know how to set this thing up. Help and suggestions would really be appreciated. Keep in mind that I cant do advanced stuff like matrices and 3D arrays. If you can keep it simple it would be awesome.
This is the main class, I have a tester class with main() that runs userInput() and menu() but theres no point in putting that in because its only 2 lines of code.
import java.util.Scanner;
public class GroceryList {
// instance variables
Scanner Price, Items, NumItems, Units;
private double myGross, myNet;
private final double STATETAX;
private double totalPrice, unitPrice;
private String itemName;
private int totalUnits;
///////////////////////////////////////////// arrays I will use
private double[] totalPrice1;
private double[] unitPrice1;
private String[] itemName1;
private int[] totalUnits1;
public GroceryList()
{
STATETAX = 0.06;
double[] totalPrice = new double[50];
double[] unitPrice = new double[50];
String[] itemName = new String[50];
int[] totalUnits = new int[50];
}
public void userInput()
{
Scanner Price = new Scanner(System.in);
Scanner Items = new Scanner(System.in);
Scanner Units = new Scanner(System.in);
Scanner NumItems = new Scanner(System.in);
int u, c, totalItems;// c is the number of items that has to equal totalItems in order for the loop to break
double price;
String item;//gets the name of the item
c=0;
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
do
{
c++ ;
System.out.print("Enter the item name : ");
item = Items.nextLine();
System.out.print("Enter the units of " + item + " you want to buy : ");
u = Units.nextInt();
System.out.print("Enter the price of a/n " + item + " : $");
price = Price. nextDouble();
/*this would make only one value appear at the receipt, which would be only one item name, one unit price, one price/unit, one total price and the other values calculated
would not appear on the receipt because you cant assign more than 1 value to a variable so thats why I need arrays.
*/
itemName = item;
totalUnits = u;
unitPrice = price;
calc(u,price,item);
}
while (c < totalItems);
}
public void calc(int u, double p, String i)
{
double total;//total amount of $ for 1 item
total = u*p;
System.out.println("Total price of " + i + " : $" + total + "\n");
grossPay(total);
totalPrice = total;
}
public void grossPay(double total)
{
double gross;
myGross += total;
}
public double tax()
{
double temp;
temp = myGross*STATETAX;
myNet = myGross - temp;
return myNet;
}
public void menu()
{
System.out.printf("%-10s %6s %11s %11s" , "ITEM :" , "UNITS :" , "PRICE :" , "TOTAL :");
System.out.println();
System.out.printf("%-11s %2d %7s $%4.2f %5s $%2.2f", itemName, totalUnits,"", unitPrice,"", totalPrice);
System.out.println();
}
public void payment()
{
System.out.println("Amount before tax : $" + myGross);
System.out.println("Amount after tax : $" + tax());
}
}//end GroceryList
Let's start with a little restructure ;)
First of all, you really don't need the array totalPrice1, the total price is the total price, there's only one...(IMHO)
Instead of initialising the arrays in the constructor, you should initialise them in the userInput method, this is when you know how many items the user will want to enter. Otherwise you will run into problems if I want to enter 51 items ;)
System.out.println("Welcome to Grocery List ! \n");
System.out.print("Enter the total number of items you want to buy (not total units !) : ");
totalItems = NumItems.nextInt();
System.out.println();
unitPrice1 = new double[totalItems];
itemName1 = new String[totalItems];
totalUnits1 = new int[totalItems];
(nb- You have bug in your original code, in the constructor, you had declared the arrays as local variables, but used the wrong names any way, this would leave the instance fields uninitialised, raising a NullPointerException)
While it's certainly not an error, it would simpler to increment c at the end of the loop...
do {
//...
calc(u, price, item);
c++;
} while (c < totalItems);
This will mean you don't need to constantly keep adjusting the position for the arrays.
In you "collection" loop, you need to assign the values the user has entered to each array...
do {
//...
itemName1[c] = item;
totalUnits1[c] = u;
unitPrice1[c] = price;
//...
} while (c < totalItems);
Having said all that, it would actually be easier to use something like a for-next loop...
for (int c = 0; c < totalItems; c++) {
//...
}
IMHO...
Finally, when you're ready, you can print the receipt by simply looping through the arrays...
for (int index = 0; index < totalItems; index++) {
double itemCost = unitPrice1[index] * totalUnits1[index];
System.out.println(itemName1[index] + " # " + unitPrice1[index] + " x " + totalUnits1[index] + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
Some feedback ;)
Having said all that, I would, personally, create yourself a simple Object which contained all the required information, for example;
public class ShoppingItem {
public String name;
public double unitPrice;
public double quantity;
}
Then, all you would need is a single array, for example...
//private double[] unitPrice1;
//private String[] itemName1;
//private int[] totalUnits1;
private ShopingItem[] items;
Then, as required, you would simply create a new instance of this item and fill it out, for example...
items[c] = new ShoppingItem();
items[c] = item;
items[c] = u;
items[c] = price;
//itemName1[c] = item;
//totalUnits1[c] = u;
//unitPrice1[c] = price;
And printing the receipt would look for like...
for (ShoppingItem item : items) {
double itemCost = item.unitPrice * item.quantity;
System.out.println(item.name + " # " + item.unitPrice + " x " + item.quantity + " = " + cost);
}
System.out.println("Total Cost: " + totalPrice);
For a more "advanced" output, I would encourage you to take a look a something like String#format and/or System.out.printf
Take a look at this example for some ideas ;)
Ideally you would (wrote this as I misread your meaning of sort):
Create an Object Item which has the fields name, totalPrice, unitPrice, totalUnits. Then in your grocery list you don't need to have 4 arrays, just one array of Items. Saves the dubious task of having to keep track of indices.
If you also create an ItemComparator class that implements Comparator you can define how they should be sorted and you can then sort your array using
Collections.sort(Arrays.asList(itemsList), new ItemComparator());
You also don't need four Scanners, you can use the same scanner since they are all on System.in

How do I write a method to calculate total cost for all items in an array?

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

Categories