Class created and Public Methods not going over to Test Method - java

I created a very simple cash register class and wanted to test it in a separate method. When I call the methods created in the class over from the test method, there is an error saying that a certain method is undefined in the class where it was created, when that is not the case. Can somebody please explain why I am getting this error? Thank you.
class:
/**
* A simulated cash register that tracks the item count and 3 the total
* amount due.
*/
public class CashRegister {
private int itemCount;
private double totalPrice;
public CashRegister() {
itemCount = 0;
totalPrice = 0;
}
public void addItem(double price) {
itemCount++;
totalPrice = totalPrice + price;
}
public double getTotal() {
return totalPrice;
}
public int getCount() {
return itemCount;
}
public void clear() {
itemCount = 0;
totalPrice = 0;
}
}
testing the class:
public class cashRegisterTester {
public static void main(String[] args) {
cashRegister register1 = new cashRegister();
register1.addItem(0.95);
register1.addItem(2.50);
System.out.println(register1.getCount());
System.out.println("Expected: 3");
System.out.printf("%.2f\n", register1.getTotal());
System.out.println("Expected: 5.40");
}
}

Get rid of the first public class cashRegister { line and the final }.

You have class within class:
public class cashRegister { /** * A simulated cash register that tracks the item count and 3 the total * amount due. */
public class CashRegister
Just delete the public class CashRegister and it should work for you.

Related

create an ArrayList from objects from another class but the same package

I am building a program with a class Item (in Item.java) and class Receipt (in Receipt.java). They both are in the same package. I want the Receipt constructor method to initialize with an ArrayList of instances of the Item object. How can I accomplish this? I keep getting a "cannot find symbol" error when I compile my code / run the Receipt.java file.
Receipt.java
package com.calculator;
import java.util.ArrayList;
// Receipt model
public class Receipt {
public ArrayList<Item> items;
// initialized with a list of item objects
public Receipt(ArrayList<Item> lineItems) {
items = lineItems;
}
// calculates total
public double totalWithSalesTax() {
}
// calculates total sales tax
public double totalSalesTax() {
double salesTax = 0;
for (Item item: items) {
salesTax = salesTax + item.calculateTax();
}
return salesTax;
}
// goes through each item and creates a string that you'd see on the receipt output
public static void main(String[] args) {
Item one = new Item("1 packet of headache pills at 9.75");
Item two = new Item("1 bottle of perfume at 18.99");
Item three = new Item("1 box of imported chocolates at 11.25");
ArrayList<Item> list = new ArrayList<>();
list.add(one);
list.add(two);
list.add(three);
System.out.println(list);
}
}
how i'm calling my code in the Receipt.java main. I get the same "cannot find symbol" error on those lines when I call them:
public static void main(String[] args) {
// the Item class is initialized with a string
Item i = new Item("1 imported box of chocolates at 10.00");
System.out.println(i.isImported);
System.out.println(i.isExempt);
System.out.println(i.quantity);
System.out.println(i.productName);
System.out.println(i.initialPrice);
System.out.println(i.calculateTax());
System.out.println(i.totalItemPriceWithTax());
}
I expected the program to recognize Item as an object in the program because they are in the same class. But I keep getting a "cannot find symbol" error when I compile my code.
For those asking about the Item class:
package com.calculator;
import java.util.ArrayList;
public class Item {
// instance variables
private boolean isImported = false;
private boolean isExempt = false;
private String productName;
private int quantity;
private double initialPrice;
// class variables
private static ArrayList<String> exemptItems = new ArrayList<String>();
// create a list of exempt items
static {
exemptItems.add("book");
exemptItems.add("chocolate");
exemptItems.add("pills");
}
public Item(String input) {
String[] strSplit = input.split(" at ");
// set initial price
initialPrice = Double.parseDouble(strSplit[1]);
// set quanitity
quantity = Integer.parseInt(strSplit[0].substring(0, strSplit[0].indexOf(" ")));
// set productname
String[] description = strSplit[0].split(" ", 2);
productName = description[1];
// set isExempt & isImported
setImported();
setExempt();
}
// method that checks if isImported
private void setImported() {
if (productName.contains("imported")) {
isImported = true;
}
}
// method that checks if isExempt
private void setExempt() {
if (getExemptItems().parallelStream().anyMatch(productName::contains)) {
isExempt = true;
}
}
// write a method that determines how much tax per item
public double calculateTax() {
double salesTax = 0.10;
double importTax = 0.05;
double precision = 0.05;
double tax = 0;
if (isImported) {
tax = tax + (initialPrice * importTax);
}
if (!isExempt) {
tax = tax + (initialPrice * salesTax);
}
// rounding to nearest .05
tax = Math.ceil(tax / precision) * precision;
return tax;
}
// write a method that represent total with tax
private double totalItemPriceWithTax() {
return this.calculateTax() + initialPrice;
}
private static ArrayList<String> getExemptItems() {
return exemptItems;
}
public static void main(String[] args) {
}
} ```
Probably you are getting this error because of this:
package com.calculator.*;
Package keyword does not support wildcards.

toString not outputting, simple hierarchy class program

I have two interfaces and two classes, Order class is parent of CoffeeBagOrder, There is no compiler error it just isn't displaying and I can't see why not
Order class:
public abstract class Order implements OrderInterface {
//variables
final static double SALES_TAX = 0.1; //not initialised by constructor
int unitWeight, numberOfUnits;
public Order() {
unitWeight=0;
numberOfUnits=0;
}
public Order(int unitWeight, int numberOfUnits) {
unitWeight=unitWeight;
numberOfUnits=numberOfUnits;
}
public void numberOfItems(int number) {
numberOfUnits=number;
}
public void unitWeight(int weight) {
unitWeight=weight;
}
}
CoffeeBagOrder class
public class CoffeeBagOrder extends Order implements Sales {
final static double PRICE_PER_KG = 5.55;
double salesBeforeTax;
double tax;
double totalSales;
public CoffeeBagOrder() {
}
public CoffeeBagOrder(int unitWeight, int numberOfUnits) {
super(unitWeight,numberOfUnits);
}
public double calculateSalesBeforeTax() {
salesBeforeTax= unitWeight*numberOfUnits*5.50;
return salesBeforeTax;
}
public double calculateSalesTax() {
tax=salesBeforeTax*0.10;
return tax;
}
public double calculateTotalSales() {
totalSales=salesBeforeTax+tax;
return totalSales;
}
//Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
}
main
import java.util.Scanner;
public class Tester {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter number of bags sold: ");
int unitWeight=sc.nextInt();
System.out.print("Enter weight of bags in kilograms: ");
int numberOfUnits=sc.nextInt();
CoffeeBagOrder customer=new CoffeeBagOrder(unitWeight,numberOfUnits);
customer.toString();
}
}
I have omitted the interfaces but they are followed accordingly , thanks in advance, also I am unsure if I have efficiently written the constructors as they are both the same?
Change your Order class constructor like below (check this.):
public Order(int unitWeight, int numberOfUnits) {
this.unitWeight=unitWeight;
this.numberOfUnits=numberOfUnits;
}
You were not updating class field in constructor! It was assigning the parameter to itself.
And modify toString in CoffeeBagOrder like below (check annotation):
#Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
Always use #Override annotation when you intend to override, to take it effect, which is best practice rather than calling toString() explicitly.
And print using
System.out.println(customer);

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

Using returns from two different methods in subclass

I'm struggling with one of the final parts of a school assignment.
I had asked this question on another question I had but did not receive an answer.
I have two methods in my super class that I need to use in my sub class and the one method must be invoked inside of the other to return a result, I'm stumped on how to do this.
public class Pay
{
private float hours;
private float rate;
private int hrsStr;
float gross;
double tax;
public void calc_Payroll()
{
if (hrsStr != 0)
gross = hrsStr + ((hours - hrsStr) * 1.33f) * rate;
else
gross = hours * rate;
}
public void tax(double a)
{
if (gross <= 399.99)
tax = .92;
else
if (gross <= 899.99)
tax = .88;
else
tax = .84;
}
public void setHours(float a)
{
hours = a;
}
public float getHours()
{
return hours;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
hrsStr = a;
}
public int getHrsStr()
{
return hrsStr;
}
}
That is the entire superclass and i need to call the calc_Payroll() method and the tax() method to the subclass, well I need tax() to be inside calc_Payroll() because I need to calculate the net pay from those two methods.
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
//I need to calculate the the net pay here.
}
}
Are you struggling with the syntax of Java?
public class Payroll extends Pay
{
float net;
#Override
public void calc_Payroll()
{
// you can call `super.calc_Payroll()`
// you can call `tax(double a)`
}
}

Divide values from a class extending number

I have a class which extends number.
public class Quantity extends Number{
}
And the class as,
public class Test{
Quantity tkphMaxValue;
Quantity tkphValue;
public Test(Quantity tkphValue, Quantity maxValue){
this.tkphValue= tkphValue;
this.maxValue= maxValue;
}
public Quantity getTkphValue() {
return tkphValue;
}
public void setTkphValue(Quantity tkphValue) {
this.tkphValue = tkphValue;
}
public Quantity getTkphMaxValue() {
return tkphMaxValue;
}
public void setTkphMaxValue(Quantity maxValue) {
this.tkphMaxValue = maxValue;
}
}
I need to divide ((getTkphValue()/getTkphMaxValue())*100) to get the percentage value.
How can I convert the Quantity object to number?
Try this:
((getTkphValue().doubleValue()/getTkphMaxValue().doubleValue())*100)
Before you do, make sure that tkphMaxValue and tkphValue are not null.

Categories