How to add two values in an array? - java

We are just starting to learn about arrays in my Java course, so I'm having problems. I want to multiply "quantity" by "cost" so it will print out the total cost, but right now it prints out 0 for the totalCost. Here is the driver:
import java.util.Scanner;
public class Problem2 {
public static void main(String[] args){
String purchase, date;
double quantity, cost;
Scanner myScanner = new Scanner (System.in);
System.out.println("How many different types of items are you purchasing?");
int answer = myScanner.nextInt();
myScanner.nextLine(); // pick up the enter key
Basket[] myBasket = new Basket[answer];
for(int j = 0; j < answer; j++) {
System.out.println("Please enter the item you purchased.");
purchase = myScanner.nextLine();
System.out.println("Please enter the date.");
date = myScanner.nextLine();
System.out.println("Please enter the quantity.");
quantity = myScanner.nextFloat();
System.out.println("Please enter the cost.");
cost = myScanner.nextFloat();
myScanner.nextLine(); // pick up the enter key
myBasket[j] = new Basket(purchase, date, quantity, cost);
}
for (int i = 0; i< answer; i++)
{
System.out.println(myBasket[i]);
}
}
}
Here is the Basket class:
import java.text.NumberFormat;
public class Basket {
private String purchase, date;
private double quantity, cost, totalCost;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
public Basket(String purchase, String date, double quantity, double cost)
{
this.purchase = purchase;
this.date = date;
this.quantity = quantity;
this.cost = cost;
}
public void Calculations()
{
totalCost = cost * quantity;
}
public String toString()
{
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
}

Add Calculations(); to toString()
public String toString()
{
Calculations();
return "Purchase: " + purchase
+ "\nDate: " + date
+"\nQuantity: " + quantity
+"\nCost:" + fmt.format(totalCost);
}
OR since the calculations method is public you can call it from the main method with myBasket[j].Calculations();
after
myBasket[j] = new Basket(purchase, date, quantity, cost);

If you want totalCost to be populated, you could call Calculations method when you are creating the instance of Baskets like:
myBasket[j] = new Basket(purchase, date, quantity, cost);
myBasket[j].Calculations();
This will now calculate the total cost and save it in in stance variable which you can print later on.

After last line in main(), add the below code,
float total=0.0;
for (int i = 0; i< answer; i++)
{
//System.out.println(myBasket[i]);
total+=myBasket[2]*myBasket[3];
}
System.out.println("total cost:"+total);

Your ”Calculations” method is not being invoked.
I thing you wanted to invoke it in the last line of the constructor.
By the way - java convention is lower case at the beginning of a method name, and it's better to name it by what it does - ”calculateTotalCost” for example

Related

dont shows the values in the array - Java

i'm doing an exercise where i have that to store objects in the array, the problem is when i'm going to print the objects of the array, dont shows the values of type String, the output is:
AFGH
3
5
2
3
5
5
1
2
5
7
my code is:
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
for(int i = 0; i < billsList.length; i++) {
System.out.println(billsList[i]);
System.out.println(billsList[i]);
System.out.println(billsList[i]);
}
}
the code of the class Bill is this:
public class Bill {
private String productCode;
private int kilosSold;
private int price;
public Bill(String productCode,int kilosSold,int price) {
this.productCode = productCode;
this.kilosSold = kilosSold;
this.price = price;
}
}
In Bill class, you have to override toString() method of the Object class.
Somewhat like:
#Override
public String toString() {
return "Product : " + productCode + " kilosold : " + kilosSold + "price : " + price;
}
or optionally you can use the #ToString of the lombok to avoid this boilerplate code.
Also, you can change your data members of class to final.
Somewhat like:
private final String productCode;
private final int kilosSold;
private final int price;
remove the nextLine and it would print fine:
System.out.println("Digit the code of the product: ");
productCode = scanner.next();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
in addition, you should override the toString method like what was answered above.
If you want to print a complete object array, and all the attributes you should use the Arrays class method "toString". If you only want one of the attributes, for example: the product code, you should use a getter method. Investigate about getter and setter methods, it will help you a lot.
public static void main(String[] args){
Bill[] billsList = new Bill[5];
Scanner scanner = new Scanner(System.in);
String productCode = " ";
int kilos = 0;
int price = 0;
for(int i = 0; i < billsList.length; i++) {
System.out.println("Digit the code of the product: ");
productCode = scanner.nextLine();
System.out.println("Digit the kilos sold: ");
kilos = scanner.nextInt();
System.out.println("Digit the price: ");
price = scanner.nextInt();
Bill bills = new Bill(productCode,kilos,price);
billsList[i] = bills;
}
System.out.println(Arrays.toString(billsList));
}

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)

Problems with adding to an ArrayList and then removing the elements

I'm sorry if this has been asked before somewhere, but I really haven't seen anything that helps with the exact question that I have. This is for school work, but I've beat myself up for 2 days over trying to figure out what I'm doing wrong, so if someone can help I would more than appreciate it.
I have a program that is basically supposed to enter the name of two sales people, show a table of their potential earnings, and finally compare the differences in their sales. I'm doing this in NetBeans IDE, and I've got all sorts of things in here trying to figure it out.
Everything works fine until I try to pull anything out of my ArrayLists. I was thinking it should be possible to store something in there, then pull it back out to do the math I need to do but I must be doing something wrong. Here's the specific Class code I'm having problems with:
class EarningDifference {
SalesPerson persons = new SalesPerson(); //Access to SalesPerson class
AnnualSales aSaleC = new AnnualSales(); //Access to AnnualSales class
ArrayList<SalesPerson> list = new ArrayList<>(); //Access to SalesPerson ArrayList
ArrayList<AnnualSales> aSales = new ArrayList<>(); //Access to AnnualSales ArrayList
AnnualSales person1EarningStr; //Person one earnings from AnnualSales ArrayList
AnnualSales person2EarningStr; //Person two earnings from AnnualSales ArrayList
Double person1Earning; //Person one earnings as double
Double person2Earning; //Person two earnings as double
String person1; //String for person one full name
String person2; //String for person two full name
Double difference; //Variable to store the difference between Person1 and Person2 sales
double totalSales; //variable for Total sales
public void people() {
person1 = list.get(0).getFirstName() + " " + list.get(0).getLastName();
person2 = list.get(1).getFirstName() + " " + list.get(1).getLastName();
System.out.println("Comparing " + person1 + " with " + person2 + ".");
}
void settotalSales(Double totalSales) {
this.totalSales = totalSales;
AnnualSales person1EarningStr = aSales.get(0);
AnnualSales person2EarningStr = aSales.get(1);
double person1Earning = person1EarningStr.doubleValue();
double person2Earning = person2EarningStr.doubleValue();
if (aSales.size() < 2) {
System.out.println("Need another person to compare");
} else if (person1Earning > person2Earning) {
difference = person1Earning - person2Earning;
System.out.println(person1 + " has earned " + difference + " more in sales than " + person2 + ".");
} else {
difference = person2Earning - person1Earning;
System.out.println(person2 + " has earned " + difference + " more in sales than " + person1 + ".");
}
}
}
Here is the class where items are added to the AnnualSales ArrayList:
public class SalaryTotal {
double fixedSalary; //Variable for the fixed salary amount
double commission; //Variable for the comission
double minimumSales; //Variable to define the minimum amount of annual sales sales persn must make to receive compensation
double maximumSales; //Variable to define the number after which commission increases
double advanceRate; //Variable used to define the rate at which compensation increases after minimum sales are met
double compensation; //Variable for the amount of compensation based on sales
double totalSalary; //Variable for the total salary
double totalSales;
Double compensationD;
SalesPerson persons = new SalesPerson();
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<Double> aSales = new ArrayList<>();
public void getCompensation(double totalSales) {
commission = .21; //The constant commission rate
minimumSales = 120000; //The constant minimum sales needed to receive compensation
maximumSales = 150000; //The constant maximum amount above which commission increases by the advanceRate
advanceRate = 1.67; //The constant at which compensation increasea after minimum sales
this.totalSales = totalSales;
if (totalSales < minimumSales) {
compensation = 0; //sets compensation to 0 if minimum sales are not met
} else if (totalSales <= 150000){
compensation = totalSales * commission + fixedSalary; //calculates total of compensation if total sales meet minimum sales
} else if (totalSales > maximumSales) {
compensation = totalSales * commission * advanceRate + fixedSalary; //calculates total compensation if total sales exceed maximum sales
}
Double compensationD = new Double(compensation);
aSales.add(compensationD);
System.out.println("Current total compensation:" + compensation);
for (int i = 0; i < aSales.size(); i++) {
System.out.println(aSales.get(i));
System.out.println("Show " + persons.makePerson1() + ".");
}
}
}
}
I'm sure this is a complete mess of bad coding, but any help would be appreciated, just ignore the random bits of odd coding I put in to try to narrow down what my issue is. Thank you so much.
The rest of the program look like this, I've also removed the bits that were just in for problem testing from previous portions
Main:
import java.util.Scanner; //Needed for scanner input
import java.text.DecimalFormat; //Needed for correct output of decimals
import java.util.ArrayList;
public class AnnualCompensation {
private static String Y;
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("$###,###.00"); //This will correctly format the money amounts
Double totalSales;
int startY;
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
Scanner start = new Scanner(System.in); //Creates scanner input
System.out.println("Are you ready to compare sales? Press 1 if yes, 2 if no."); //Prints out entry command
startY = start.nextInt();
switch (startY){
case 1:
InputClass inputs = new InputClass();
inputs.getInputs();
break;
case 2:
System.out.println("Thank you anyway!");
System.exit(0);
break;
default:
System.out.println("You have selected neither Y or N, please try again.");
System.exit(0);
}
SalaryTotal calculator = new SalaryTotal(); //Calls class SalaryTotal
PossibleCompensation table = new PossibleCompensation(); //Calls class PossibleCompensation
}
}
Possible Compensation:
public class PossibleCompensation {
SalesPerson persons = new SalesPerson();
ArrayList<SalesPerson> list = new ArrayList<>();
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
DecimalFormat df = new DecimalFormat("$###,###.00"); //This will correctly format the money amounts
double commission; //Variable for the comission
double minimumSales; //Variable to define the minimum amount of annual sales sales persn must make to receive compensation
double maximumSales; //Variable to define the number after which commission increases
double advanceRate; //Variable used to define the rate at which compensation increases after minimum sales are met
double compensation; //Variable for the amount of compensation based on sales
double totalSales; //Variable for sales person annual sale
public void settotalSales(double totalSales) {
for (int i = 0; i < list.size(); i++)
this.totalSales = totalSales; //Sets the input from AnnualCompensation to totalSales in this class
commission = .21; //The constant commission rate
minimumSales = 120000; //The constant minimum sales needed to receive compensation
maximumSales = 150000; //The constant maximum amount above which commission increases by the advanceRate
advanceRate = 1.67; //The constant at which compensation increasea after minimum sales
String heading1 = "Total Sales"; //variable to print a header for the table
String heading2 = "Total Compensation"; //variable to print a header for the table
System.out.print("\nBelow is a table based on possible commissions if sales increase:\n"); //Prints instructions
System.out.printf("\n%20s %20s", heading1, heading2); //prints header and formats spacing
for (double i=totalSales; i <= (totalSales * 1.5); i+= 5000) { //FOR loop for calculating and constructing table
if (i < minimumSales) {
compensation = 0; //sets compensation to 0 if minimum sales are not met
} else if (i <= 150000){
compensation = i * commission; //calculates total of compensation if total sales meet minimum sales
} else if (i > maximumSales) {
compensation = i * commission * advanceRate; //calculates total compensation if total sales exceed maximum sales
}
System.out.printf("\n%20s %15s", df.format(i), df.format(compensation) + "\n"); //Prints out the table
}
}
}
class SalesPerson {
String firstName;
String lastName;
String totalSalesStr;
ArrayList<SalesPerson> list = new List<>();
SalesPerson class:
public SalesPerson() {
this.firstName = firstName;
this.lastName = lastName;
this.totalSalesStr = totalSalesStr;
}
SalesPerson(String firstName, String lastName, String totalSalesStr) {
this.firstName = firstName;
this.lastName = lastName;
this.totalSalesStr = totalSalesStr;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public String getTotalSalesStr() {
return this.totalSalesStr;
}
public Double getTotalSales() {
Double totalSales = Double.parseDouble(totalSalesStr);
return totalSales;
}
public String makePerson1() {
String person1 = list.get(0).getFirstName() + " " + list.get(0).getLastName();
return person1;
}
public String makePerson2() {
String person2 = list.get(1).getFirstName() + " " + list.get(1).getLastName();
return person2;
}
#Override
public String toString() {
return ("Sales person " + this.getFirstName() + " " + this.getLastName() + " has annual sales of " + this.getTotalSalesStr() + ".");
}
}
class AnnualSales {
Double compensationD;
AnnualSales person1EarningStr;
AnnualSales person2EarningStr;
ArrayList<AnnualSales> aSales = new ArrayList<AnnualSales>();
public AnnualSales() {
this.compensationD = compensationD;
}
public AnnualSales(Double compensationD) {
this.compensationD = compensationD;
}
public Double getCompensationD() {
return this.compensationD;
}
public AnnualSales getperson1EarningStr() {
person1EarningStr = aSales.get(0);
return person1EarningStr;
}
public AnnualSales getperson2EarningStr() {
person2EarningStr = aSales.get(1);
return person2EarningStr;
}
#Override
public String toString() {
return ("please show us" + compensationD);
}
}
Input class:
class InputClass {
String firstName;
String lastName;
Double totalSales;
String totalSalesStr;
CopyOnWriteArrayList<SalesPerson> list = new CopyOnWriteArrayList<>();
public void getInputs() {
for(double i=0; i < 2; i++){
Scanner persFN = new Scanner(System.in); //Creates scanner input
System.out.println("Enter sales person's first name:"); //Prints out entry command
String firstName = persFN.next();
Scanner persLN = new Scanner(System.in); //Creates scanner input
System.out.println("Enter sales person's last name:"); //Prints out entry command
String lastName = persLN.next();
Scanner input = new Scanner(System.in); //Creates scanner input
System.out.println("Enter Total Sales:"); //Prints out entry command
totalSales = input.nextDouble();
String totalSalesStr = totalSales.toString();
list.add(new SalesPerson(firstName, lastName, totalSalesStr));
SalaryTotal calculator = new SalaryTotal(); //Calls class SalaryTotal
calculator.getCompensation(totalSales);
PossibleCompensation table = new PossibleCompensation(); //Calls class PossibleCompensation
table.settotalSales(totalSales);
EarningDifference earning = new EarningDifference();
earning.settotalSales(totalSales);
}
}
}
I think that should be everything related!
Make sure you have override equals() method in your Classes. As a good practice always make sure you have override both equals() and hashCode().
Why?
From Java doc.
Removes the first occurrence of the specified element from this list,
if it is present. If the list does not contain the element, it is
unchanged. More formally, removes the element with the lowest index i
such that (o==null ? get(i)==null : o.equals(get(i))) (if such an
element exists). Returns true if this list contained the specified
element (or equivalently, if this list changed as a result of the
call).
If your ArrayList element not a String(more generally if it is not a inbuilt Java class), You need to override equals() method.

Using default and non default constructors in my application

I'm new to java and have a question about default and non default constructors. My professor wants us to use the default constructor for creation of object BOOK1, and then use the non default constructor for BOOK2, BOOK3 and BOOK4. I know a constructor is used with the creation of an object, but I guess I don't understand how i'm supposed to differentiate between the two. My class code is as follows, where I have both a default and non default constructor:
import java.text.DecimalFormat;
public final class BOOKItem {
DecimalFormat intFormat = new DecimalFormat("000");
DecimalFormat doubleFormat = new DecimalFormat("$#,##0.00");
private int bookID;
private int numberInStock;
private double price;
private double totalValueOfStock;
private int code;
private String genre = "";
public BOOKItem() {
bookID = 0;
numberInStock = 0;
price = 0;
code = 0;
}
public BOOKItem(int newID, int newStock, double newPrice, int newCode) {
setID(newID);
setStock(newStock);
setCode(newCode);
setPrice(newPrice);
}
public void setStock (int newStock) {
if (newStock >= 1 && newStock <=5000) {
numberInStock = newStock;
}
else {
numberInStock = 0;
}
}
public void setCode (int newCode) {
if (newCode > 0) {
code = newCode;
}
}
public void setID (int newID) {
if (newID >=11 && newID <= 111111) {
bookID = newID;
}
else {
bookID = 0;
}
}
public void setPrice (double newPrice) {
if (newPrice >= 1.0 && newPrice <=150.0) {
price = newPrice;
}
else {
price = 0;
}
}
public int getID () {
return bookID;
}
public int getNumberInStock () {
return numberInStock;
}
public int getCode () {
return code;
}
public double getPrice () {
return price;
}
public double calcTotalValue () {
totalValueOfStock = numberInStock * price;
return totalValueOfStock;
}
public double getTotalValue () {
return totalValueOfStock;
}
public void display() {
switch (code)
{
case 1:
genre = "Romance";
break;
case 2:
genre = "Adventure";
break;
case 3:
genre = "Sci-Fi";
break;
case 4:
genre = "Mystery";
break;
}
System.out.println("Display:");
System.out.println("Book ID: " + bookID + " NumInStock: " + numberInStock + " Code: " + genre + " Price: " +
price + " TotalStockValue: " + calcTotalValue());
}
}
Here is my application that uses the constructors(sorry about the break in the class code, i dunno why its doing that):
import java.util.Scanner;
public class Project7 {
public static void main(String[] args) {
int bookID;
int numberInStock;
double price;
int code;
Scanner keyboard = new Scanner(System.in);
BOOKItem BOOK1, BOOK2, BOOK3, BOOK4;
BOOK1 = new BOOKItem();
BOOK2 = new BOOKItem();
BOOK3 = new BOOKItem();
BOOK4 = new BOOKItem();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD ID(<11 or >111111)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK1.setID(bookID);
BOOK1.setStock(numberInStock);
BOOK1.setCode(code);
BOOK1.setPrice(price);
BOOK1.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD STOCK(>5000)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2.setID(bookID);
BOOK2.setStock(numberInStock);
BOOK2.setCode(code);
BOOK2.setPrice(price);
BOOK2.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use a BAD PRICE(>150.0)");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK3.setID(bookID);
BOOK3.setStock(numberInStock);
BOOK3.setCode(code);
BOOK3.setPrice(price);
BOOK3.display();
System.out.println("Enter in a blank separated list: ID, number in stock, quality, price" +
"- use ALL GOOD DATA");
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK4.setID(bookID);
BOOK4.setStock(numberInStock);
BOOK4.setCode(code);
BOOK4.setPrice(price);
BOOK4.display();
}
}
Am I doing something incorrect with the creation of my objects? How do I use the non default constructor for BOOK2, BOOK3 and BOOK4? I created it, but perhaps i'm using it incorrectly. Any feedback would be greatly appreciated.
When you use
BOOK1 = new BOOKItem();
You are calling the default constructor (Construction without having any arguments)
After taking user input you would call the Non Default Constructor
bookID = keyboard.nextInt();
numberInStock = keyboard.nextInt();
code = keyboard.nextInt();
price = keyboard.nextDouble();
BOOK2 = new BOOKItem(bookID, numberInStock, price, code);
Use the above code to use the Parameterized Constructor (Non Default constructor)
This is called constructor overloading.
So for the objects you want to assign default values you call the default constructor
For the object you have information available with variables you sent them in the constructor that you have defined with parameters, To assign that value

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