Calculate total from array - java

Two questions:
1. How do I create a method called getTotal() that traverses through the array and counts the total of the votes for all Candidates?
2. Where and how to create the method printResults() , that should transverse through the array and creates a table with columns for Candidate name, followed by votes received, and then percentage of total votes
Candidate
public class Candidate
{
// instance variables
private int numVotes;
private String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
public int getTotal(Candidate[] election)
{
}
}
TestCandidate
public class TestCandidate
{
public static void printVotes(Candidate[] election)
{
for(int i = 0; i < election.length; i++)
System.out.println(election[i]);
}
public int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[5];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
System.out.println(" Results per candidate ");
System.out.println("______________________________");
System.out.println();
printVotes(election);
System.out.println("The total of votes in election: " + getTotal() );
}
}

public int getTotal(Candidate[] election)
{
int total = 0;
for( Candidate candidate : election ) {
total += candidate.votes();
}
return total;
}
This method and printResults() method in my opinion should go to some wrapper class that gathers all Candidates. For example like this:
class CandidatesList {
private Candidate[] candidates;
public CandidatesList(Candidate[] candidates) {
this.candidates = candidates;
}
public int getTotal()
{
int total = 0;
for( Candidate candidate : candidates) {
total += candidate.votes();
}
return total;
}
public String toString() {
StringBuilder builder = new StringBuilder();
int total = getTotal();
for( Candidate candidate : candidates) {
builder.append( String.format( "%20s | %5d | %.2f %%\n",
candidate.getName(), candidate.votes(), candidate.votes() / total );
}
return builder.toString();
}
}
You can use it like this:
CandidatesList list = new CandidatesList(election);
System.out.print(list);
System.out.format("Total votes: %d\n", list.getTotal());

Related

How to merge two alike items within the ArrayList?

So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?

Static function for sum & compareTo

Ok so basically this is my program it's about Students & Student Groups;
Each student has a name, ID and marks/points;
The program is working fine but what's missing is that the SUM function in the class StudentsGroup needs to be static and to take a parameter of the "Group" of which you need the sum of points. My problem is that when I put the function and the ArrayList to static, the function returns both of the groups score combined and I don't know how to make it work
//the program works correctly and returns the correct values about
everything; i only get those errors when i try to change the
sumOfPoints function to static
the two files that i have are:
Group 1:
61662126 Laurel 50
61662213 Mark 35.5
61662345 Yanny 67
61662127 Larry 27
61662125 Kevin 87.5
and Group 2:
61662126 Jason 70
61662213 Josh 25.5
61662345 Bobby 57
61662127 Megan 17
61662125 Drake 86.5
the correct output should be:
Total points of Group1: 267.0
Total points of Group2: 256.0
Comparing Group1 to Group2: 1
but when i put it to static it returns 523 in both which is both of the groups combined and i don't understand what im doing wrong
public interface IFile
{
public void Load();
}
public class Student implements Comparable<Student>
{
private int facnum;
private String name;
private double points;
public Student(int fn, String n, double p)
{
this.facnum = fn;
this.name = n;
this.points = p;
}
public void SetFN(int fn)
{
this.facnum = fn;
}
public void SetName(String n)
{
this.name = n;
}
public void SetPoints(double p)
{
this.points = p;
}
public int GetFN()
{
return this.facnum;
}
public String GetName()
{
return this.name;
}
public double GetPoints()
{
return this.points;
}
public boolean equals(Object s)
{
if (this.GetFN() != ((Student)s).GetFN())
{
return false;
}
return true;
}
public int compareTo(Object s)
{
if(this.GetFN() < ((Student)s).GetFN())
{
return -1;
}
if(this.GetFN() > ((Student)s).GetFN())
{
return 1;
}
return 0;
}
public String toString()
{
return "Faculty Number: " + this.facnum + " Name: " + this.name + " Points: " + this.points + " \n";
}
}
import java.io.*;
import java.util.*;
public class StudentsGroup implements IFile, Comparable<Object>
{
private String groupname;
private List<Student>oStudent = new ArrayList<Student>();
public StudentsGroup(String filename)
{
this.groupname = filename;
Load();
}
public void Load(){
try
{
Scanner sc=new Scanner(new File(this.groupname));
while(sc.hasNextLine())
{
oStudent.add(new Student(sc.nextInt(),sc.next(),
sc.nextDouble()));
}
sc.close();
}
catch(IOException e)
{
System.out.println("Input/Output Error...");
}
}
public void printColl()
{
System.out.println(oStudent.toString());
}
public List<Student> sortedListFN()
{
Collections.sort(oStudent);
return oStudent;
}
public double sumOfPoints()
{
double sum = 0.00;
for(Iterator<Student> it= oStudent.iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints() < ((StudentsGroup) s).sumOfPoints())
{
return -1;
}
if(this.sumOfPoints() > ((StudentsGroup) s).sumOfPoints())
{
return 1;
}
return 0;
}
public static void main(String[] args)
{
StudentsGroup oGroup1 = new StudentsGroup("Group1.txt");
oGroup1.printColl();
System.out.println("Sorted order by FN: " + oGroup1.sortedListFN() + "\n");
StudentsGroup oGroup2 = new StudentsGroup("Group2.txt");
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints() + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints() + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
}
}
edit//the static method that i tried is changing oStudent to static:
private static List<Student>oStudent = new ArrayList<Student>();
obviously changing the sum function to static & editing the compareTo method:
public static double sumOfPoints(Object s)
{
double sum = 0.00;
s = new ArrayList<Student>(oStudent);
for(Iterator<Student> it= ((List<Student>) s).iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints(this) < ((StudentsGroup) s).sumOfPoints(s))
{
return -1;
}
if(this.sumOfPoints(this) > ((StudentsGroup) s).sumOfPoints(s))
{
return 1;
}
return 0;
}
and the output:
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints(oGroup1) + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints(oGroup2) + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
and the output starts returning 523
Your static method overwrites s with the inner object of that particular instance class:
s = new ArrayList<Student>(oStudent);
I think your mistake is here. This is not how you use a static method of class. The correct way to do it is StudentsGroup.sumOfPoints(yourObjectHere). A static method should not know about any field of a particular instance.

How to Override a method based on a condition

In my BOOKING class I have this method to calculate the total amount
public void calcTotal(){
total = amount*priceperbooking;
}
I created a subclass called BOOKING_APPLICATION and I want to override the calcTotal() method if amount > 5 then it must subtract 15% of the total
Here is what I tried but it does not work:
public void calcTotal(){
if (super.amount>5) {
super.total = super.total-(15/100.0*super.total);
}
}
When I run it its giving me the original total, not taking out 15%
What am I doing wrong
Edit: Here is the code of my main class
public class Diving_Adventures{
static BOOKING obj1 = new BOOKING();
static BOOKING_APPLICATION obj2 = new BOOKING_APPLICATION();
public static void main(String[] args) {
obj1.setName();
obj1.setNumber();
obj1.setAmount();
obj1.setPriceperbooking();
obj1.calcTotal();
obj2.calcTotal();
JOptionPane.showMessageDialog(null, obj1.toString());
}
}
I'm assuming by obj1.calcTotal() it will calculate the total and by obj2.calcTotal it will take out the 15% but it does not work
Here is the full code of my BOOKING class:
private String name;
private int number;
public int amount;
public double priceperbooking;
public double total;
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public int getAmount() {
return amount;
}
public double getPriceperbooking() {
return priceperbooking;
}
public void setName() {
this.name = JOptionPane.showInputDialog("Enter the name");;
}
public void setNumber() {
this.number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
}
public void setAmount() {
this.amount = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount"));
}
public void setPriceperbooking() {
this.priceperbooking = Double.parseDouble(JOptionPane.showInputDialog("Enter the price per bookin"));;
}
public void calcTotal(){
total = amount*priceperbooking;
}
#Override
public String toString() {
return "Customer name: "+name+"\n"+"number"+ number + "\namount=" + amount +
"\n priceperbooking=" + priceperbooking + "\n total=" + total ;
}
In your derived class:
public void calcTotal() {
total = super.calcTotal();
if (amount > 5) {
total = total - (15/100.0 * total);
}
}
You are mising on calculating the total first, as mentioned.

required boolean found no arguments [duplicate]

This question already has answers here:
required: double [] found: no arguments
(4 answers)
Closed 6 years ago.
hoping to find a solution before i put my head through my monitor.
What I am trying to do is use a boolean to make a sell function.
basically I want it not to sell stock if there is less than 0 (print error message)
if there is i want to +1 to numSold and -1 to numInStock.
when i try im getting an error
"method sellCopy in class item cannot be applied to given types; required boolean; found no arguments reason actual and formal argument list differ in length"
public abstract class Item
{
private String name;
private double price;
private int numInStock;
private int numSold;
public Item(String inName, double inPrice)
{
name = inName;
price = inPrice;
numInStock = 0;
numSold = 0;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public int getNuminStock()
{
return numInStock;
}
public int getNumSold()
{
return numSold;
}
public void receiveStock(int amount)
{
numInStock = numInStock + amount;
}
public boolean sellCopy(boolean sellCopy)
{
if (numInStock <= 0)
{
sellCopy = true;
numSold = numSold +1;
numInStock = numInStock -1;
return true;
}
else
{
sellCopy = false;
System.out.println("Stock unavalable");
return false;
}
}
}
public class Game extends Item
{
private int MaxPlayers;
public Game(String inName, int inMaxPlayers, double inPrice)
{
super(inName, inPrice);
MaxPlayers = inMaxPlayers;
}
public String toString()
{
return " Game " + super.toString() + " Maximum Player: " + MaxPlayers + "\n";
}
import java.util.*;
public class Shop
{
private ArrayList<Item> items = new ArrayList<Item>();
public boolean addItem(Item newItem)
{
if (!findItem(newItem.getName()))
{
items.add(newItem);
return true;
}
else
{
System.out.println(" Error - an item with that name " +newItem.getName() + " already exists");
return false;
}
}
public boolean findItem(String searchName)
{
for (Item nextItem : items)
{
//might be searchName//
if (searchName.equals(nextItem.getName()))
{
System.out.println(nextItem);
return true;
}
}
return false;
}
public void listItems()
{
System.out.println("The shop contains the following items***\n");
for (Item nextItem : items)
{
System.out.println(nextItem);
}
}
public void calcTotalSales()
{
double total = 0;
for (Item nextItem : items)
{
total += nextItem.getNumSold() * nextItem.getPrice();
}
System.out.println("****The total number sold is worth $" + total);
System.out.println("****");
}
}
public class test
{
public static void main (String args[])
{
//create the shop
Shop myShop = new Shop();
//create a Game and add it to the shop
Game game1 = new Game("Chess", 2, 39.95);
myShop.addItem(game1);
//order and get stock
game1.receiveStock(5);
//sell some items
game1.sellCopy();
//the bastard right here//
//print information about shop
myShop.calcTotalSales();
//test error conditions
Game game2 = new Game("Chess", 2, 39.95);
myShop.addItem(game2); //should fail as a Chess item is already in the shop
//eg2.sellCopy();
}
}
If you look at the code,
game1.sellCopy();
That sellCopy method needs a boolean. You need to pass it.
game1.sellCopy(true);// for example. Pass your actual value.

Creating an ArrayList of Employees

I have three classes
employee
production workers
shift supervisor class
My idea is to make production and shift supervisor extend the employee class and then create another class, EmployeeList to fill it with information about production workers and shift supervisors.
How can i get the names and info from employee class to iterate into an arraylist?
How can i add a random list of employees more than half being prod. workers and the rest shift supervisors?
Employee:
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Enum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C" };
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
}
ProductionWorker:
import java.util.Random;
public class ProductionWorker extends Employee {
public double HourlyRate;
public ProductionWorker()
{
super();
HourlyRate = 0;
}
public static void main(String[] args) {
ProductionWorker pw = new ProductionWorker();
Random rnd = new Random();
int count =0;
// adding random Employees.....
while(count<5)
{
int num= rnd.nextInt(Enum.length);
int decimal = rnd.nextInt(10);
double dec = decimal/10;
pw.setEmployeeName(Ename[num]);
pw.setEmployeeNumber(Enum[num]);
pw.setEmployeehireyear(rnd.nextInt(35) + 1980);
pw.setEmployeeweeklyearning(rnd.nextInt(5000) + 5000);
pw.setHourlyRate(rnd.nextInt(44) + 6 + dec);
System.out.println("EmployeeName: " + pw.getEmployeeName() + "\nEmployeeNumber: " + pw.getEmployeeNumber() +
"\nHireYear: " + pw.gethireyear() + "\nWeeklyEarning: " + pw.getWeeklyEarning() +
"\nHourlyRate: " + pw.getHourlyRate() +"\n");
count++;
}
}
public double getHourlyRate()
{
return this.HourlyRate;
}
public void setHourlyRate(double hourlyrate)
{
this.HourlyRate = hourlyrate;
}
}
ShiftSupervisor:
import java.util.Random;
public class ShiftSupervisor extends Employee{
public double YearlySalary;
public int GoalsCleared;
public ShiftSupervisor()
{
super();
YearlySalary = 0;
}
public static void main(String[] args) {
ShiftSupervisor S = new ShiftSupervisor();
Random rnd = new Random();
int count =0;
// adding random Employees.....
System.out.println("Adding Employees..");
while(count<5)
{
int num= rnd.nextInt(Enum.length);
S.setEmployeeName(Ename[num]);
S.setEmployeeNumber(Enum[num]);
S.setEmployeehireyear(rnd.nextInt(35) + 1980);
S.setEmployeeweeklyearning(rnd.nextInt(100) * 100);
S.setYearlySalary(rnd.nextInt(40000) + 40000);
System.out.println("EmployeeName:" + S.getEmployeeName() + "\nEmployeeNumber: " + S.getEmployeeNumber() +
"\nHireYear: " + S.gethireyear() + "\nWeeklyEarning: " + S.getWeeklyEarning() +
"\nearlySalary: " + S.getYearlySalary() +"\n");
count++;
}
}
// returns yearly salary
public double getYearlySalary()
{
return this.YearlySalary;
}
// returns goals cleared
public int getGoalsCleared()
{
return this.GoalsCleared;
}
// set yearly salary
public void setYearlySalary(double yearlysalary)
{
this.YearlySalary = yearlysalary;
}
}
The first thing I would do is have all necessary fields set in the constructor. If an Employee doesn't "exist" until it has a name, then that should be part of the constructor.
Then, I would suggest you consider renaming some of your fields. When I first saw Enum as a String[] and highlighted as a type, it took me a moment to figure out what exactly was going on. Renaming it to employeeNumbers could solve this.
Next, I think you should have an EmployeeGenerator class whose sole purpose is generating Employees.
public class EmployeeGenerator {
public ProductionWorker generateProductionWorker() {
Random rng = new Random();
int numberOfEmployeeNames = employeeNames.length;
String employeeName = employeeNames[rng.nextInt(numberOfEmployeeNames)];
int numberOfEmployeeNumbers = employeeNumbers.length;
String employeeNumber = employeeNumbers[rng.nextInt(numberOfEmployeeNumbers)];
ProductionWorker worker = new ProductionWorker(employeeName, employeeNumber);
int yearHired = rng.nextInt(100) + 1900;
worker.setHireYear(yearHired);
int hourlyRate = rng.nextInt(20) + 10;
worker.setHourlyRate(hourlyRate);
// any other fields...
return worker;
}
// method to generate shift supervisor
}
And then you can simply do
public static void main(String[] args) {
Random rng = new Random();
int numberOfEmployeesToGenerate = 1000;
int minimumNumberOfProductionWorkers = numberOfEmployeesToGenerate / 2;
int numberOfProductionWorkersToGenerate =
minimumNumberOfProductionWorkers + rng.nextInt(100);
int numberOfSupervisorsToGenerator =
numberOfEmployeesToGenerate - numberOfProductionWorkersToGenerate;
List<Employee> employees = new ArrayList<>();
EmployeeGenerator generator = new EmployeeGenerator();
for (int i = 0; i < numberOfProductionWorkersToGenerate; i++) {
ProductionWorker worker = generator.generateProductionWorker();
employees.add(worker);
}
for (int i = 0; i < numberOfSupervisorsToGenerate; i++) {
Supervisor supervisor = generator.generateSupervisor();
employees.add(supervisor);
}
}
This should hopefully give you a point in the right direction. This isn't perfect code, and there are other ways to refactor this to make it more maintainable and performant.
When you say you want to add a random list of employees, What do you mean exactly?
Currently you instantiate only one ProductionWorker and one ShiftSupervisor, change the values of the member variables, and print some text to StdOut.
Do you want to store instances in a list or is the console output sufficient?
Also, you have two main-methods. Which one will be performed? It might be better to have one Main class as an entry point for your application and from there create the instances.
In general you can do something like that:
public class Main {
public static void main(String[] args) {
List<Employee> emps = new ArrayList<>();
for (int i = 0; i < 5; i++) {
//create new employee
emps.add(newEmployee);
}
//do something with list
}
}

Categories

Resources