If the quantity is not positive it should be set to 0.
If the price per item is not positive it should be set to 0.0.
Hwever when I enter a negative number it keeps setting my variable negative and not Zero.
This is my class package com.company;
/**
* Created by juliodiaz on 5/7/16.
*/
public class Invoice {
private String partNumber;
private String partDescription;
private int partQuantity;
private double partPrice;
public Invoice(String partNumber, String partDescription, int partQuantity, double partPrice) {
this.partNumber = partNumber;
this.partDescription = partDescription;
this.partQuantity = partQuantity;
this.partPrice = partPrice;
}
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartDescription() {
return partDescription;
}
public void setPartDescription(String partDescription) {
this.partDescription = partDescription;
}
public int getPartQuantity() {
return partQuantity;
}
public void setPartQuantity(int partQuantity) {
this.partQuantity = partQuantity;
}
public double getPartPrice() {
return partPrice;
}
public void setPartPrice(double partPrice) {
this.partPrice = partPrice;
}
public double invoiceAmountMethod(double partPrice, int partQuantity) {
if (partQuantity < 0 || partPrice < 0.0) {
this.partQuantity = 0;
return partPrice * partQuantity;
}
else
return partPrice * partQuantity;
}
}
//Main method
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Invoice myTruck = new Invoice("A101", "Wheels", -2, 100.00);
System.out.println(myTruck.getPartDescription());
System.out.println(myTruck.getPartNumber());
System.out.println(myTruck.getPartQuantity());
System.out.println(myTruck.getPartPrice());
double price = myTruck.getPartPrice();
int quantity = myTruck.getPartQuantity();
System.out.println("The total cost is " + myTruck.invoiceAmountMethod(price, quantity));
}
}
OUTPUT
Wheels
A101
-2
100.0
The total cost is -200.0
You're assigning:
this.partQuantity = 0;
but you return:
return partPrice * partQuantity;
(the parameters that were passed to the method).
you can fix it by returning:
return this.partPrice * this.partQuantity;
and you really shouldn't pass any parameters to this method.
Here is what you need.
public double invoiceAmountMethod(double partPrice, int partQuantity) {
return (partQuantity < 0 || partPrice < 0.0)?0.0:partPrice * partQuantity;
}
Related
If i have 2 classes the first one is BasicHamburger
public class BasicHamburger {
private String breadRollType;
private String meat;
private boolean lettuce;
private boolean tomato;
private boolean carrot;
private boolean cheese;
private int numberOfAdditions;
private int price;
public BasicHamburger(String breadRollType , String meat ,int price){
this.breadRollType = breadRollType;
this.meat = meat;
this.price = price;
lettuce = false;
tomato = false;
carrot = false;
cheese = false;
numberOfAdditions = 0;
}
public void addLettuce(){
lettuce = true;
incrementNumberOfAdditions();
}
public void addTomato(){
tomato = true;
incrementNumberOfAdditions();
}
public void addCarrot(){
carrot = true;
incrementNumberOfAdditions();
}
public void addCheese(){
cheese = true;
incrementNumberOfAdditions();
}
public int getNumberOfAdditions(){
return numberOfAdditions;
}
protected int incrementNumberOfAdditions(){
return ++numberOfAdditions;
}
public boolean isLettuce() {
return lettuce;
}
public boolean isTomato() {
return tomato;
}
public boolean isCarrot() {
return carrot;
}
public boolean isCheese() {
return cheese;
}
public int getBasicHamburgerPrice(){
return price;
}
public int getLettucePrice(){
return 20;
}
public int getTomatoPrice(){
return 15;
}
public int getCheesePrice(){
return 40;
}
public int getCarrotPrice(){
return 10;
}
public int getTotalBasicHamburgerPrice(){
if(isCarrot()){
price = price + 10;
}
if(isCheese()){
price = price + 40;
}
if(isTomato()){
price = price + 15;
}
if(isLettuce()){
price = price + 20;
}
return price;
}
public void displayBurgerDetailsWithPrices(){
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
System.out.println("Basic Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Basic Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
the second class is HealthyBurger
public class HealthyBurger extends BasicHamburger{
private boolean onion;
private boolean bacon;
public HealthyBurger(){
super("Brown Rye ","Mutton",30);
onion = false;
bacon = false;
}
public boolean isOnion() {
return onion;
}
public boolean isBacon() {
return bacon;
}
public void addOnion(){
onion = true;
incrementNumberOfAdditions();
}
public void addBacon(){
bacon = true;
incrementNumberOfAdditions();
}
public int getOnionPrice(){
return 15;
}
public int getBaconPrice(){
return 20;
}
#Override
public int getTotalBasicHamburgerPrice() {
int newPrice = super.getTotalBasicHamburgerPrice();
if(isBacon()){
newPrice += 20;
}
if(isOnion()){
newPrice +=15;
}
return newPrice;
}
#Override
public void displayBurgerDetailsWithPrices() {
if(isCarrot()){
System.out.println("Carrot addition = "+getCarrotPrice());
}
if(isCheese()){
System.out.println("Cheese addition = "+getCheesePrice());
}
if(isTomato()){
System.out.println("Tomato addition = "+getTomatoPrice());
}
if(isLettuce()){
System.out.println("Lettuce addition = "+getLettucePrice());
}
if(isOnion()){
System.out.println("Onion addition = "+getOnionPrice());
}
if(isBacon()){
System.out.println("Bacon addition = "+getBaconPrice());
}
System.out.println("Healthy Hamburger Total Price Without Additions = "+getBasicHamburgerPrice());
System.out.println("Healthy Hamburger Total Price After Additions= "+getTotalBasicHamburgerPrice());
}
}
in the main i have written this code
public class Main {
public static void DisplayBurger(BasicHamburger burger){
burger.displayBurgerDetailsWithPrices();
}
public static void main(String[] args) {
BasicHamburger ham1 = new BasicHamburger("x","beef",20);
ham1.addCarrot();
ham1.addCheese();
ham1.addLettuce();
ham1.addTomato();
HealthyBurger ham2 = new HealthyBurger();
ham2.addOnion();
ham2.addBacon();
BasicHamburger test = ham2;
DisplayBurger(test);
}
}
My confusion is the test variable can access displayBurgerDetailsWithPrices() function inside HealthyBurger class and can call the isOnion which is inside that function. Whereas if i decided to write that code inside the main i can not access the isOnion() function.
BasicHamburger newBurger = new HealthyBurger();
newBurger.isOnion();
To make the question clear and right to the point , why accessing a function inside a subclass through a overriden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
BasicHamburger newBurger = new HealthyBurger();
boolean onion = false;
if(newBurger instanceof HealthyBurger)
onion = ((HealthyBurger).isOnion());
To make the question clear and right to the point, why accessing a function inside a subclass through an overridden function is possible whereas accessing that function directly is not possible when using a variable of the superclass?
It calles Polymophism. The object reference BasicHamburger newBurger refers to the instance of class BasicHamburger or any of its children. It means that by default you have access only to the methods declared in BasicHamburger or any of its parent. If you want to call the children's method, you have to cast this reference to the required type.
I would redesign your code, because in general case if you use casting, then it looks like a design problem (repeat: in general; sometimes it really needed).
public abstract class Burger {
protected final String breadRollType;
protected final String meat;
protected final int basePrice;
protected final Set<Ingredient> ingredients;
protected Burger(String breadRollType, String meat, int basePrice, Set<Ingredient> ingredients) {
this.breadRollType = breadRollType;
this.meat = meat;
this.basePrice = basePrice;
this.ingredients = ingredients == null || ingredients.isEmpty() ? Set.of() : Set.copyOf(ingredients);
}
public final int getBasePrice() {
return basePrice;
}
protected int getIngredientsPrice() {
return ingredients.stream()
.map(Ingredient::getPrice)
.mapToInt(i -> i)
.sum();
}
public int getTotalPrice() {
return basePrice + getIngredientsPrice();
}
public final int getTotalIngredients() {
return ingredients.size();
}
public final boolean hasIngredient(Ingredient ingredient) {
return ingredient != null && ingredients.contains(ingredient);
}
public void printDetailsWithPrices() {
System.out.println(breadRollType + ' ' + meat);
System.out.println("----");
System.out.println("Basic price: " + basePrice);
System.out.println("Ingredients price: " + getIngredientsPrice());
ingredients.forEach(ingredient -> System.out.format("-> %s price: %d\n",
ingredient.getTitle(), ingredient.getPrice()));
System.out.println("Total price: " + getTotalPrice());
}
protected interface Ingredient {
String getTitle();
int getPrice();
}
}
public class HealthyBurger extends Burger {
public HealthyBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
ONION("Onion", 15),
BACON("Bacon", 20);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public class PopularBurger extends Burger {
protected PopularBurger(String breadRollType, String meat, int basePrice, Set<Burger.Ingredient> ingredients) {
super(breadRollType, meat, basePrice, ingredients);
}
public enum Ingredient implements Burger.Ingredient {
LETTUCE("Lettuce", 20),
TOMATO("Tomato", 25),
CARROT("Carrot", 10),
CHEESE("Cheese", 40);
private final String title;
private final int price;
Ingredient(String title, int price) {
this.title = title;
this.price = price;
}
#Override
public String getTitle() {
return title;
}
#Override
public int getPrice() {
return price;
}
}
}
public static void main(String... args) {
PopularBurger popularBurger = new PopularBurger("x", "beef", 20,
Set.of(PopularBurger.Ingredient.CARROT,
PopularBurger.Ingredient.CHEESE,
PopularBurger.Ingredient.LETTUCE,
PopularBurger.Ingredient.TOMATO));
HealthyBurger healthyBurger = new HealthyBurger("Brown Rye", "Mutton", 30,
Set.of(HealthyBurger.Ingredient.ONION,
HealthyBurger.Ingredient.BACON));
PopularBurger one = popularBurger;
one.printDetailsWithPrices();
System.out.println();
HealthyBurger two = healthyBurger;
two.printDetailsWithPrices();
System.out.println();
boolean withOnion = two.hasIngredient(HealthyBurger.Ingredient.ONION);
System.out.println(withOnion);
}
x beef
----
Basic price: 20
Ingredients price: 95
-> Cheese price: 40
-> Carrot price: 10
-> Lettuce price: 20
-> Tomato price: 25
Total price: 115
Brown Rye Mutton
----
Basic price: 30
Ingredients price: 35
-> Onion price: 15
-> Bacon price: 20
Total price: 65
true
I have been working on an assignment and i am stuck at here. Basically i have 1 class which defines all functions and members.
And another class to initialize and manipulate objects.
Here is my first class code.
public class cyryxStudent_association {
String studentID, studentName, studentCourse_level, studentTitle;
int course_completed_year;
static double registration_fee;
double activity_fee;
double total_amt;
//Default constructor
cyryxStudent_association ()
{
studentID = "Null";
studentName = "Null";
studentCourse_level = "Null";
studentTitle = "Null";
course_completed_year = 0;
}
//Parameterized Constructor
cyryxStudent_association (String id, String name, String course_level, String title, int ccy)
{
this.studentID = id;
this.studentName = name;
this.studentCourse_level = course_level;
this.studentTitle = title;
this.course_completed_year = ccy;
}
//Getters
public String getStudentID ()
{
return studentID;
}
public String getStudentName ()
{
return studentName;
}
public String getStudentCourse_level ()
{
return studentCourse_level;
}
public String getStudentTitle ()
{
return studentTitle;
}
public int getCourse_completed_year ()
{
return course_completed_year;
}
public double getRegistration_fee ()
{
return registration_fee;
}
public double getActivity_fee ()
{
return findActivity_fee(registration_fee);
}
public double getTotal_amt ()
{
return total_amt(registration_fee, activity_fee);
}
//Setters
public void setStudentID (String id)
{
studentID = id;
}
public void setStudentName (String name)
{
studentName = name;
}
public void setStudentCourse_level (String course_level)
{
studentCourse_level = course_level;
}
public void setStudentTitle (String title)
{
studentTitle = title;
}
public void setCourse_completed_year (int ccy)
{
course_completed_year = ccy;
}
//Find registration fee method
public static double findRegistration_fee (String course_level)
{
if (course_level.equalsIgnoreCase("Certificate"))
{
registration_fee = 75;
}
else if (course_level.equalsIgnoreCase("Diploma"))
{
registration_fee = 100;
}
else if (course_level.equalsIgnoreCase("Degree"))
{
registration_fee = 150;
}
else if (course_level.equalsIgnoreCase("Master"))
{
registration_fee = 200;
}
return registration_fee;
}
//Find activity method
public static double findActivity_fee (double registration_fee)
{
return registration_fee * 0.25;
}
//Find total amount
public static double total_amt (double registration_fee, double activity_fee)
{
return registration_fee + activity_fee;
}
//To string method
public String toString ()
{
return "ID: "+getStudentID()+"\nName: "+getStudentName()+"\nCourse Level:
"+getStudentCourse_level()+"\nTitle: "+getStudentTitle()+"\nCourse Completed Year:
"+getCourse_completed_year()+"\nRegistration Fee: "+getRegistration_fee()+"\nActivity Fee:
"+getActivity_fee()+"\nTotal Amount: "+getTotal_amt ();
}
}
And here is my second class code.
import java.util.Scanner;
public class test_cyryxStudent_association {
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num, i;
System.out.println("Welcome!");
System.out.println("\nEnter the number of students: ");
num = sc.nextInt();
sc.nextLine();
cyryxStudent_association Std[] = new cyryxStudent_association[num];
for (i = 0; i < Std.length; i++)
{
System.out.println("\nEnter ID: ");
Std[i].setStudentID(sc.nextLine());
System.out.println("Enter Name: ");
Std[i].setStudentName(sc.nextLine());
System.out.println("Enter Course Level [Certificate, Diploma, Degree, Master]: ");
Std[i].setStudentCourse_level(sc.nextLine());
System.out.println("Enter Title: ");
Std[i].setStudentTitle(sc.nextLine());
Std[i].getRegistration_fee();
Std[i].getActivity_fee();
Std[i].getTotal_amt();
}
for (i = 0; i < Std.length; i++)
{
System.out.println("\nStudent " + i + 1 + " Information");
System.out.println("===================================");
Std[i].toString();
}
sc.close();
}
}
I get an error when values in the for loop. Can someone help me? I'm pretty new to programming and studying java for 2 months now. What am i doing wrong?
Here is my objectives.
Create an array of objects and get user input for number of objects to be manipulated.
Read and display array of object values.
Thank you!
You have to initialize the objects of your array.
After the line:
cyryxStudent_association Std[] = new cyryxStudent_association[num];
do a for loop like:
for(i = 0; i<std.length; i++){
std[i] = new cyryxStudent_association();
}
I understand that I do not have anything in my main method yet so nothing will execute, that is the second part to the assignment.
My question is, I'm getting an error in the computeDiscount method where I'm calling the computeNumCases method. The error i'm getting is
variable numCases might not have been initialized
so I need help figuring that error out.
Also, help in the computeCost method would be very helpful as well.
public class Customer {
private String customerLastName;
private String candyType;
private int numCandyBars;
private double costPerBar;
private int NUMBERPERCASE = 12;
public static void main(String[] args) {
}
public Customer() {
}
public Customer(String name, String type, int numCandyBars, double costPerBar) {
//this.name = name;
candyType = type;
this.numCandyBars = numCandyBars;
this.costPerBar = costPerBar;
}
public static double getCostPerBar(double costPerBar) {
return costPerBar;
}
public static int getNumCandyBars(int numCandyBars) {
return numCandyBars;
}
public String getCandyType() {
return candyType;
}
public String GetCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String name) {
this.customerLastName = name;
}
public void setNumCandyBars(int num) {
this.numCandyBars = num;
}
public void setCandyType(String candyType) {
this.candyType = candyType;
}
public void setCostPerBar(double cost) {
costPerBar = cost;
}
public int computeNumCases(int numCases) {
numCases = numCandyBars / NUMBERPERCASE;
return numCases;
}
public int computeNumIndividuals(int numIndividuals) {
numIndividuals = numCandyBars % NUMBERPERCASE;
return numIndividuals;
}
public int computeDiscount(int discount) {
int numCases = computeNumCases(numCases);
if (numCases < 20)
discount = 100;
else if (numCases < 50)
discount = 85;
else
discount = 75;
return discount;
}
public double computeCost(double totalCost) {
return computeNumCases(numCases) * getCostPerBar(costPerBar) * (NUMBERPERCASE * discount / 100.00) + computeNumIndividuals(numIndividuals) * getCostPerBar(costPerBar);
}
}
I do not know why the if statement is not working in the program.
When order is greater than bulkorder, it still returns 0.
Do you think there is a problem with the code I have written which is shown below?
public class ShoeStoreOrder{ //ShoeStoreOrder .java
// private method
private String typeofshoe ;
private String season ;
private double cost ;
private int bulkOrderQuantity;
private int discount;
private int order;
//constructor
public ShoeStoreOrder(String t,String s,double c,int b,int d,int o){
typeofshoe = t;
season = s;
cost = c;
bulkOrderQuantity = b;
discount = d;
order = o;
}
//get Method
public String gettypeofshoe(){
return typeofshoe;
}
public String getseason(){
return season;
}
public double getcost(){
return cost;
}
public int getbulkOrderQuantity(){
return bulkOrderQuantity;
}
public int getdiscount(){
return discount;
}
public int getorder(){
return order;
}
//set method
public void settypeofshoe(String t){
typeofshoe=t;
}
public void setseason(String s){
season=s;
}
public void setcost(double c){
cost=c;
}
public void setbulkOrderQuantity(int b){
bulkOrderQuantity=b;
}
public void setorder(int o){
order=o;
}
//other method
//overload method
public double gettotaldiscount(){
if(order()>bulkOrderQuantity()){
return order*cost*(discount/100);
}
else{
return 0;
}
}
public double gettotalamount(){
return order*cost-gettotaldiscount();
}
}
order and bulkOrderQuantity are instance variable and not a method. () are used when calling a method and not when referencing a variable:
if(order()>bulkOrderQuantity()){
change it to
if(order>bulkOrderQuantity){
You have skipped case when order value equals bulkOrderQuantity:
public double gettotaldiscount() {
if (order >= bulkOrderQuantity) {
return order * cost * discount / 100;
} else {
return 0;
}
}
//Check input and results:
public static void main(String[] args) {
ShoeStoreOrder sso;
System.out.println("No discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 1);
System.out.println(sso.gettotalamount());
System.out.println("After discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 5);
System.out.println(sso.gettotalamount());
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 50);
System.out.println(sso.gettotalamount());
}
Output:
No discount
20.0
After discount
90.0
900.0
I have this arrayList that i need to first sort from greatest to least by both item price and then after i need to sort it by the amount of items sold. Whats the easiest way to accomplish this? thanks!
import java.util.*;
public class salesPerson {
//salesPerson fields
private int salespersonID;
private String salespersonName;
private String productType;
private int unitsSold = 0;
private double unitPrice;
//Constructor method
public salesPerson(int salespersonID, String salespersonName, String productType, int unitsSold, double unitPrice)
{
this.salespersonID = salespersonID;
this.salespersonName = salespersonName;
this.productType = productType;
this.unitsSold = unitsSold;
this.unitPrice = unitPrice;
}
//Accessor for salesPerson
public int getSalesPersonID()
{
return salespersonID;
}
public String getSalesPersonName()
{
return salespersonName;
}
public String getProductType()
{
return productType;
}
public int getUnitsSold()
{
return unitsSold;
}
public double getUnitPrice()
{
return unitPrice;
}
public double getTotalSold()
{
return unitsSold * unitPrice;
}
//Mutoators for salesPerson
public void setSalesPersonID(int salespersonID)
{
this.salespersonID = salespersonID;
}
public void setSalesPersonName(String salespersonName)
{
this.salespersonName = salespersonName;
}
public void setProductType(String productType)
{
this.productType = productType;
}
public void setUnitsSold(int unitsSold)
{
this.unitsSold += unitsSold;
}
public void setUnitProce(double unitPrice)
{
this.unitPrice = unitPrice;
}
public static void main(String[] args)
{
ArrayList<salesPerson> salesPeople = new ArrayList<salesPerson>();
Scanner userInput = new Scanner(System.in);
boolean newRecord = true;
boolean showReport = true;
do
{
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
System.out.println("Please enter the Salesperson Inoformation.");
System.out.print("Salesperson ID: ");
salespersonID = userInput.nextInt();
System.out.print("Salesperson Name: ");
salespersonName = userInput.next();
System.out.print("Product Type: ");
productType = userInput.next();
System.out.print("Units Sold: ");
unitsSold = userInput.nextInt();
System.out.print("Unit Price: ");
unitPrice = userInput.nextDouble();
if(salesPeople.size() == 0)
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
else
{
for(int i=0; i < salesPeople.size(); i++)
{
if(salesPeople.get(i).getSalesPersonID() == salespersonID)
{
salesPeople.get(i).setUnitsSold(unitsSold);
break;
}
else
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
break;
}
//System.out.println(salesPeople.get(i).getSalesPersonName());
}
}
System.out.print("Would you like to enter more data?(y/n)");
String askNew = userInput.next();
newRecord = (askNew.toLowerCase().equals("y")) ? true : false;
}
while(newRecord == true);
Write a custom comparator:
public SalesPersonComparator implements Comparator<salesPerson> {
public int compare(final salesPerson p1, final salesPerson p2) {
// get the comparison of the unit prices (in descending order, so compare p2 to p1)
int comp = new Double(p2.getUnitPrice()).compareTo(new Double(p1.getUnitPrice()));
// if the same
if(comp == 0) {
// compare the units sold (in descending order, so compare p2 to p1)
comp = new Integer(p2.getUnitsSold()).compareTo(new Integer(p1.getUnitsSold()));
}
return comp;
}
}
Edit (thanks to #Levenal):
Then use Collections.sort() to sort your list.