I started this code and I don't know how to finish it. I need to make the class and test driver for a collection of SalesPeople and their data. I created the salespeople class and constructor. i created the accessors and mutators. I need help combing into this into an arrayList class for my test driver. PLEASE HELP (:
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;
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
do{
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();
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);
}
}
You have already created a variable called salesPeople.
After taking all the inputs from user create a new object of SalesPerson and add to the salesPeople at the end in while loop.
Check the Below code for more clarity.
.....
SalesPerson tmp = new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}while (newRecord == true)
....
Put this inside your do-while-loop after you have all the data. You need to create each SalesPerson after you have the data, otherwise the values (id, name...) will just be lost and overwritten in the next loop-iteration
salesPeople.add(new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice));
Because the arraylist salesPeople takes objects of salesPerson you will first want to create an object of salesPerson and then add the salesPerson to the salesPeople arraylist.
salesPerson sp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(sp);
Put that at the end of your do while right before you ask them if you want to create a new salesPerson.
add below 2 lines(creating sp object and adding it to list) at the end of do that is before the line below
System.out.print("Would you like to enter more data?(y/n)");
SalesPerson sp = new SalesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(sp);
Related
I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class
My goal is to get an amount for an item and a description of that item. I want to get 10 inputs and their values. I don't know how to store their info without asking for one then the other. I want to be able to ask for the user to input the item then price and then store each of those values.
I was trying to create an array of objects to enter and then was suggested to use arraylists which I kind of understand but don't know how to implement in this case.
import java.util.ArrayList;
public class Invoice {
private ArrayList<Item> listOfItems;
public Invoice() {
listOfItems = new ArrayList<Item>();
}
public void addItem(Item item) {
listOfItems.add(item);
}
public double calculateNetItemCost() {
double netCost = 0;
for(Item currentItem : listOfItems) {
netCost += currentItem.getCost();
}
return netCost;
}
public double calculateTax(double taxRateAsADecimal) {
return calculateNetItemCost() * taxRateAsADecimal;
}
public double calculateGST() {
double GST = calculateNetItemCost() * 0.05;
return GST;
}
public double calculatePST() {
double PST = calculateNetItemCost() * 0.07;
return PST;
}
public double calculateTotalCost() {
double total = calculateGST() + calculatePST() + calculateNetItemCost();
return total;
}
}
public class Item {
private double amount;
private String description;
public Item(String description, double amount) {
this.amount = amount;
this.description = description;
}
public String toString() {
return description + ", $" + String.format("%.2f", amount);
}
public double getCost() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
import java.util.Scanner;
import java.util.ArrayList;
public class CustomerBuild {
public static void main(String[] args) {
ArrayList<String> description = new ArrayList<String>();
ArrayList<Double> amount = new ArrayList<Double>();
Scanner input = new Scanner(System.in);
String userInput;
Item testItem = new Item("Apples", 4.00);
System.out.println(testItem);
Invoice testInvoice = new Invoice();
testInvoice.addItem(testItem);
double subTotal = testInvoice.calculateNetItemCost();
System.out.println(subTotal);
double GST = testInvoice.calculateGST();
System.out.println("GST: " + GST);
double PST = testInvoice.calculatePST();
System.out.println("PST: " + PST);
System.out.println("Total cost: " + testInvoice.calculateTotalCost());
}
}
This code snippet is what are you looking for. Asking the user for input then initializing the object using the values
Scanner input = new Scanner(System.in);
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
Item testItem = new Item(description, price);
For Looping:
for(int i =1;i<10;i++) {
System.out.println("Please enter description(e.g.apple,banana,orange):");
String description =input.nextLine();
System.out.println("Please enter Price(e.g.4.0,5.99):");
Double price = scanner.nextDouble();
testInvoice.addItem(new Item(description, price));
}
So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.
Main Class
public class Main {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
int uinput;
Library nag;
try{
nag = new Library();
do{
System.out.println("Type 1 to add a book.");
System.out.println("Type 2 to show how many books are borrowed.");
uinput = keyb.nextInt();
if (uinput==1){
nag.addBook();
}
if (uinput==2){
nag.statistics();
}
}while (uinput > 0);
}
catch(Exception e){
System.out.println("Invalid entry.");
}
}//end of main
}//end of class
Book Class
public class Book {
private String Title;
private String Author;
private String ISBN;
private String Publisher;
private String Publication_Date;
private String Price;
private int Quantity;
private String Status;
public Book(){
Title= "";
Author="";
ISBN="";
Publisher="";
Publication_Date="";
Price="";
Quantity=1;
Status="IN-STOCK";
}
//getters
public String gettitle(){return Title;}
public String getauthor(){return Author;}
public String getisbn(){return ISBN;}
public String getpublisher(){return Publisher;}
public String getpublication_date(){return Publication_Date;}
public String getprice(){return Price;}
public int getquantity(){return Quantity;}
public String getstatus(){return Status;}
//setters
public void settitle(String t){Title = t;}
public void setauthor(String a){Author = a;}
public void setisbn(String is){ISBN = is;}
public void setpublisher(String p){Publisher = p;}
public void setpublication_date(String pd){Publication_Date = pd;}
public void setprice(String pr){Price = pr;}
public void setquantity(int q){Quantity = q;}
public void setstatus(String s){Status = s;}
}//end of class
Library Class
public class Library {
private ArrayList<Book> BookList;
public Library(){
BookList = new ArrayList<Book>();
}//end of constructor 1
public Library(ArrayList<Book> l) {
BookList = l;
}//end of constructor 3
public void addBook(){
try{
Scanner keyb = new Scanner(System.in);
Book bo = new Book();
System.out.println("Type the title: ");
String title_input;
title_input = keyb.nextLine();
bo.settitle(title_input);
System.out.println("Type the author: ");
String author_input;
author_input = keyb.nextLine();
bo.setauthor(author_input);
System.out.println("Type the isbn: ");
String isbn_input;
isbn_input = keyb.nextLine();
bo.setisbn(isbn_input);
System.out.println("Type the publisher: ");
String publisher_input;
publisher_input = keyb.nextLine();
bo.setpublisher(publisher_input);
System.out.println("Type the publication date: ");
String publication_date_input;
publication_date_input = keyb.nextLine();
bo.setpublication_date(publication_date_input);
System.out.println("Type the price: ");
String price_input;
price_input = keyb.nextLine();
bo.setprice(price_input);
System.out.println("Type the quantity: ");
int quantity_input = Integer.parseInt(keyb.nextLine());
if (quantity_input >= 0){
bo.setquantity(quantity_input);
if (quantity_input > 0){
bo.setstatus("IN_STOCK");
}
if(quantity_input == 0){
bo.setstatus("BORROWED");
}
BookList.add(bo);
System.out.println("Book added successfully.");
}
}catch(Exception e){
System.out.println("Invalid entry");
}//end of addBook()
public void statistics(){
Book bo = new Book();
int counter = 0;
for(int i=0; i < BookList.size();i++){
bo= BookList.get(i);
int holdquantity = bo.getquantity();
if (holdquantity < 1){
counter++;
}
}
double substraction=BookList.size() - counter;
double division= substraction/BookList.size();
double percentage = division * 100;
System.out.print(percentage + "%");
}//end of statistics()
}//end of class
The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.
Let's say your Book class is as follows:
package com.company;
public class Book {
private int quantity;
public Book(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
And your Main is as follows:
package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main (String[]args) {
List<Book> bookList = new ArrayList<>(){{
add(new Book(4));
add(new Book(0));
add(new Book(3));
add(new Book(7));
add(new Book(0));
add(new Book(0));
add(new Book(1));
add(new Book(9));
add(new Book(0));
add(new Book(5));
}};
int booksOutOfStock = 0;
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getQuantity() == 0)
booksOutOfStock++;
}
double percentage = 100d / bookList.size() * booksOutOfStock;
System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
percentage);
}
}
So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.
Output of code above:
Out of total 10 books, 4 are out of stock, which makes 40.00%
OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:
catch(Exception e){
System.out.println("Invalid entry");
} --> } <--- (added)
//end of addBook()
And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:
double division= (double)counter/BookList.size();
double percentage = division * 100;
System.out.printf("%.2f", percentage);
I am facing a common compilation error with Cannot find symbols in java. The methods from the class Product cannot be used in the main class. The code is below. I have tried to pass the class in any possible ( to my knowledge means) but with no luck.
The error i get is:
CashRegisterTester.java:108: error: cannot find symbol
double iprice = products[i].getPrice();
^
symbol: variable products
location: class CashRegister
1 error
Here's the code.
import java.util.Scanner;
class CashRegisterTester {
public static void main(String[] args) {
Product[] products = new Product[5];
products[0] = new Product();
products[0].setCode(0);
products[0].setName("psomi");
products[0].setPrice(0.50);
products[1] = new Product();
products[1].setCode(1);
products[1].setName("gala");
products[1].setPrice(1.30);
products[2] = new Product();
products[2].setCode(2);
products[2].setName("mila");
products[2].setPrice(1.80);
products[3] = new Product();
products[3].setCode(3);
products[3].setName("zaxari");
products[3].setPrice(2.40);
products[4] = new Product();
products[4].setCode(4);
products[4].setName("krasi");
products[4].setPrice(13.20);
for (int i = 0; i < 5; i++)
System.out.println("\n Product code: " + products[i].getCode() + " \n Product Name: " + products[i].getName() + "\n Product Price: " +
products[i].getPrice());
System.out.println("Which product would you like to buy?");
Scanner myscanner = new Scanner(System.in);
int iEntered;
iEntered = myscanner.nextInt();
CashRegister register = new CashRegister(products);
register.recordPurchase(iEntered);
System.out.println("Would you like to buy something more? [y/n]");
String answer;
answer = myscanner.next();
while (answer.equals('y')) {
System.out.println("Which product would you like to buy?");
register.recordPurchase(iEntered);
System.out.println("Would you like to buy something more? [y/n]");
answer = myscanner.next();
}
System.out.println("How much money will you give?");
double pay = myscanner.nextDouble();
register.enterPayment(pay);
double change = register.giveChange();
System.out.println(change);
// register.finalReceipt();
}
}
class Product{
//Product fields
public int code;
public String name;
public double price;
//Getters & setters
public int getCode(){
return code;
}
public void setCode(int scode){
code = scode;
}
public String getName(){
return name;
}
public void setName(String sname){
name = sname;
}
public double getPrice(){
return price;
}
public void setPrice(double sprice){
price = sprice;
}
}
public class CashRegister extends Product{
public CashRegister(Product[] products){
purchase = 0;
payment = 0;
}
public void recordPurchase(int i){
double iprice = products[i].getPrice;
double total = purchase + iprice;
purchase = total;
}
public void enterPayment(double amount){
payment = amount;
}
public double giveChange(){
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
private double purchase;
private double payment;
}
The products variable is declared nowhere. This is why you get this exception.
Declare products as a private member of the CashRegister class and initialize it in the CashRegister constructor. See the code below:
public class CashRegister extends Product {
public CashRegister(Product[] products){
purchase = 0;
payment = 0;
this.products=products; // Initialize private member
}
public void recordPurchase(int i){
double iprice = products[i].getPrice();
double total = purchase + iprice;
purchase = total;
}
public void enterPayment(double amount){
payment = amount;
}
public double giveChange(){
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
private double purchase;
private double payment;
private Product[] products; // Declare private member
}
One last note, to prevent resource leaks, NEVER forget to close a Scanner.
So add myscanner.close(); at the end of the main method in the CashRegister class.
I've written this code and everything seems to be correct but unfortunately its not giving the correct units sold. im trying to find out if the salesperson ID exists and update that record. Sometimes it prints the right information and sometimes it does not.
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 = 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;
int salespersonID;
String salespersonName;
String productType;
int unitsSold = 0;
double unitPrice;
do{
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);
}
else
{
salesPerson tmp = new salesPerson(salespersonID, salespersonName, productType, unitsSold, unitPrice);
salesPeople.add(tmp);
}
//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);
for(int i=0; i < salesPeople.size(); i++) {
System.out.println(salesPeople.get(i).getSalesPersonName() + ": "+salesPeople.get(i).getUnitsSold());
}
}
}
This method is probably wrong:
public void setUnitsSold(int unitsSold){
this.unitsSold = this.unitsSold + unitsSold;
}
Replace it by:
public void setUnitsSold(int unitsSold){
this.unitsSold = unitsSold;
}
You also have a problem on your main() method: The for creates a new SalesPerson instance for each element that has a different id from the one you've received on the input.
It's not related with your problem, but you should always (and I mean ALWAYS) start the name of Java classes with capital letters.