Converting the same String value into an Object - java

I have an object share:
Share tea = new Share("TEA", "Common", 0, 100);
ArrayList<Share> shares = new ArrayList<Share>();
shares.add(tea);
What I'd like to do is, reading parameters from the keybord, convert directly the "tea" string into a share tea object :
Trade trade = new Trade( tea, Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
What should I put instead of tea because my constructor is waiting a Share and not a String. The user is entering a string and I don't need ton create a new instance, I have to use the Share object "tea" that already exists.
The Share.java class :
public class Share {
private String shareSymbol = "";
private String type = "Common";
private double lastDividend = 0;
private double fixedDividend = 0;
private int parValue = 0;
// Calucul values
public String getShareSymbol() {
return shareSymbol;
}
public String getType() {
return type;
}
public double getLastDividend() {
return lastDividend;
}
public double getFixedDividend() {
return fixedDividend;
}
public int getParValue() {
return parValue;
}
// Constructor without Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend, int parValue) {
this.shareSymbol = shareSymbol;
this.type = type;
this.lastDividend = lastDividend;
this.parValue = parValue;
}
// Constructor with Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend,
int fixedDividend, int parValue) {
this(shareSymbol, type, lastDividend, parValue);
this.fixedDividend = fixedDividend / 100.0;
}
public String toString(){
String result="";
result += shareSymbol + " "+type + " " + lastDividend + " " + fixedDividend + " " + parValue + "\n";
return result;
}
}
The Trade.java class :
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
// The class trade allows the stock, the quantity and the price to be intialised
public class Trade {
Share share;
private int quantity;
double price;
private double dividendYield;
private double pERatio;
private boolean buyOrSell;
private Date tradeDate;
public Trade(Share share, boolean buyOrSell, int quantity, double price) {
this.share = share;
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
}
public String toString() {
String result = "";
result += "stock symbol : " + share.getShareSymbol() + " \n";
result += "Buy or Sell : " + buyOrSell + " \n";
result += "quantity :" + quantity + " \n";
result += "price : " + price + " \n";
result += "Dividend Yield : " + dividendYield + " \n";
result += "P/E Ratio : " + pERatio + " \n";
result += "tradeDate : " + tradeDate + " \n\n";
return result;
}
public Share getShare() {
return share;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public double getDividendYield() {
return dividendYield;
}
public double getpERatio() {
return pERatio;
}
public Date getTradeDate() {
return tradeDate;
}
public double calcDividendYield() {
if ("Common".equalsIgnoreCase(share.getType())) {
dividendYield = share.getLastDividend() / price;
} else if ("Preferred".equalsIgnoreCase(share.getType())) {
dividendYield = share.getFixedDividend() * share.getParValue()
/ price;
}
return dividendYield;
}
public double calcPERatio() {
if (dividendYield > 0)
pERatio = price / dividendYield;
return pERatio;
}
}

Your constructor is waiting a share. So give it:
/* Read parameters from keyboard, stock in s1, s2, i1 and i2 variables */
Trade trade = new Trade( new Share(s1,s2,i1,i2), Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
Otherwise you can implement a method (in Share class) that do it for you
public static Share stringToShare(String s1, String s2, int t1, int t2){
return new Share(s1, s2, t1, t2);
}
And then:
Trade trade = new Trade( Share.stringToShare(...), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
EDIT: better use real variable names that means something, not s1, s2, etc.

I've got around of this, by creating a new constructor :
Trade trade = new Trade(shares, stockSymbol, Boolean.parseBoolean(buyOrSell),
Integer.parseInt(quantity), Double.parseDouble(tradePrice));
This is then the new constructor :
public Trade(ArrayList<Share> shares, String stockSymbol,
boolean buyOrSell, int quantity, double price) {
Iterator<Share> iter = shares.iterator();
int index = -1;
while (iter.hasNext()) {
Share share = iter.next();
index++;
if (stockSymbol.equalsIgnoreCase((share.getShareSymbol()))) {
this.share = shares.get(index);
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
break;
}
}
}
It's a bit complacated, because I had also to create a new method to get the Share for the given String(having the same name, for instance). But that does What i needed.
It would be cleaner though to make it with Java Reflection, without having to create a new constructor. So if any one have an idea with a code more clever, I would be happy!

Related

toString method for arrays

I am struggling with an actually very easy task, which is print out items from an item array like:
arr[3,4,2,5]
0 items (0 kg)
0 items (1 kg)
0 items (2 kg)
and so on.
This is what I have done, but my program will not print anything :( Heeelp me please.
import java.util.ArrayList;
import java.util.Arrays;
public class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int[] arr = new int[items.size()];
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
int itemsWeight = 0;
for(Item i: items){
itemsWeight += i.getWeight();
}
if(itemsWeight + item.getWeight() <= this.maxWeight){
items.add(item);
}
}
public void array() {
for(Item item: items){
int index = item.getWeight();
this.arr[index] += 1;
}
}
public String toString() {
String returnValue = "";
for(int i = 0; i < arr.length; i++){
returnValue = arr[i] + " items " + i + " kg";
}
return returnValue;
}
}
public class Item {
private int weight;
private String name;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return this.name + "(" + String.valueOf(this.weight) + ")";
}
}
Here is my main class, but it will not print anything:
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase.toString());
suitcase.addItem(book);
System.out.println(suitcase);
suitcase.addItem(phone);
System.out.println(suitcase);
suitcase.addItem(brick);
System.out.println(suitcase);
}
}
Notes:
You do not need to call suitcase.toString() while printing the suitcase object. When System.out.println(suitcase); is implicitly gets converted into System.out.println(suitcase.toString());.
You can make your design simpler by having a variable to keep track of the total weight in the suitcase. Also, create a variable in Item to keep track of item's count in the suitcase.
You do not need int[] arr. It is simply adding unwanted complexity. Remove it.
It is better to use enhanced for loop if you can do so.
Given below is the code incorporating the points mentioned above:
import java.util.ArrayList;
class Suitcase {
private ArrayList<Item> items = new ArrayList<>();
private final int maxWeight;
private int totalWeight;
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
if (totalWeight + item.getWeight() <= maxWeight) {
int index = items.indexOf(item);
if (index == -1) {// It means the item does not exist in the suitcase
items.add(item);
}
// If the item already exists, do not add it's entry again; just update its
// count and the totalWeight of the suitcase
totalWeight += item.getWeight();
item.setCount(item.getCount() + 1);
System.out.println(item.getName() + " was added in the suitcase");
} else {
System.out.println(item.getName() + " can not be accommodated in the suitcase.");
}
}
public String toString() {
String returnValue = "";
for (Item item : items) {
returnValue += "No. of " + item.getName() + " in the suitcase = " + item.getCount()
+ ", its total weight = " + item.getCount() * item.getWeight() + "kg\n";
}
if (returnValue.isEmpty()) {
returnValue = "The suitcase is empty.";
} else {
returnValue += "Total weight of the suitcase = " + totalWeight + "kg";
}
return returnValue;
}
}
class Item {
private int weight;
private String name;
private int count;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Item [weight=" + weight + ", name=" + name + ", count=" + count + "]";
}
}
public class Main {
public static void main(String[] args) {
Item book = new Item("Lord of the rings", 2);
Item phone = new Item("Nokia 3210", 1);
Item brick = new Item("brick", 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase);
suitcase.addItem(book);
suitcase.addItem(phone);
suitcase.addItem(brick);
suitcase.addItem(phone);
suitcase.addItem(book);
System.out.println(suitcase);
}
}
Output:
The suitcase is empty.
Lord of the rings was added in the suitcase
Nokia 3210 was added in the suitcase
brick can not be accommodated in the suitcase.
Nokia 3210 was added in the suitcase
Lord of the rings can not be accommodated in the suitcase.
No. of Lord of the rings in the suitcase = 1, its total weight = 2kg
No. of Nokia 3210 in the suitcase = 2, its total weight = 2kg
Total weight of the suitcase = 4kg
Make sure to change your "toString()" function, currently it is only printing the last value, change it to:
public String toString(){
String returnValue ="";
for(int i = 0; i<arr.length;i++ ){
returnValue += arr[i] + " items " +i+" kg"; //notice its '+='
}
return returnValue;
}
You initialize your arr with value 0. Note that the initial size of new ArrayList() is 0. Take a look at this example:
import java.util.ArrayList;
class Main {
private static ArrayList<Object> items = new ArrayList();
private static int[] arr = new int[items.size()];
public static void main(String[] args) {
System.out.println(items.size()); # => 0
System.out.println(arr.length); # => 0
}
}
As a result when you call System.out.println(suitcase) the for loop in Suitcase's toString() method iterates over exactly 0 elements - therefore not outputting anything.

java - Function in class

I need to write a function to College department :
Add function adds additional lecturer.
Action returns false if there is no place to add additional lecturer, and at the same true if the lecturer was successfully added.
What I had written so far:
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
The function does not work properly, It always returns true (because that the Max Lecturer always bigger than sum).
main:
public class main {
public static void main(String[]args){
Lecturer[] L1 = new Lecturer[]{new Lecturer("David",3,"Banana",1001)};
Lecturer[] L2 = new Lecturer[]{new Lecturer("Yossi",5,"apple",1002)};
Lecturer[] L3 = new Lecturer[]{new Lecturer("Y",2,"t",1003)};
College myCollege = new College("College1",20,L1,3);
//System.out.println(myCollege);
//myCollege.allLecturer=L2;
//System.out.println(myCollege);
myCollege.newLecturer(L1);
myCollege.newLecturer(L2);
myCollege.newLecturer(L3);
}
}
class College (Function here):
public class College {
public String name;
public int numOfLecturer;
public Lecturer[] allLecturer;
public int maxLecturer;
// constructor
public College(String Name, int NumOfLecturer, Lecturer[] AllLecturer,
int MaxLecturer) {
this.name = Name;
this.numOfLecturer = NumOfLecturer;
this.allLecturer = AllLecturer;
this.maxLecturer = MaxLecturer;
}
public College(String Name) {
this.name = Name;
}
public College(Lecturer[] AllLecturer) {
this.allLecturer = AllLecturer;
}
public boolean newLecturer(Lecturer[] AllLecturer) {
int MaxLecturer = 0;
MaxLecturer = this.maxLecturer;
int sum = 0;
sum += 1;
if (sum < MaxLecturer) {
System.out.println("true");
return true;
}
else {
System.out.println("false");
return false;
}
}
#Override
public String toString() {
String lecturers = "";
for (Lecturer lecturer : allLecturer) {
lecturers += lecturer;
}
return "[Name College: " + name + "] " + " [num Of Lecturer: "
+ numOfLecturer + "]" + " [all Lecturer: " + lecturers + "]"
+ " [max Lecturer " + maxLecturer + "]";
}
}
class Lecturer:
public class Lecturer {
public String name;
public int numOfTimesPenFalls;
public String favoriteIceCream;
public int autoNumber;
// constructor
public Lecturer(String Name, int NumOfTimesPenFalls,
String FavoriteIceCream, int AutoNumber) {
this.name = Name;
this.numOfTimesPenFalls = NumOfTimesPenFalls;
this.favoriteIceCream = FavoriteIceCream;
this.autoNumber = AutoNumber;
}
public Lecturer(String Name) {
this.name = Name;
}
#Override
public String toString() {
return "[name: " + name + "] " + " [num Of Times Pen Falls: "
+ numOfTimesPenFalls + "] " + " [favorite Ice Cream: "
+ favoriteIceCream + "] " + " [auto Number: " + autoNumber
+ "]";
}
}
And finally how can I print it?
Like this gives a compiler error:
myCollege.newLecturer("David",2,"Apple",1004);
thank you.
You're new; you need a lot of help.
Start by learning and following Java coding standards. Variable names should start with lower case. Classes start with upper. Deviations from that make your code hard to read.
Your method is wrong. You need something like this inside that class:
private static final int MAX_LECTURERS = 3;
private int numLecturers = 0;
private Lecturer [] lecturers = new Lecturer[MAX_LECTURERS];
public boolean addLecturer(Lecturer lecturer) {
boolean addedLecturer = false;
if (this.numLecturers < MAX_LECTURERS) {
this.lecturers[numLecturers++] = lecturer;
addedLecturer = true;
}
return addedLecturer;
}
Here's how you use this method:
Lecturer newLecturer = new Lecturer("foo", 1, "bar", 3);
college.addLecturer(newLecturer);
Please stop with all that array nonsense. The array is inside the College class.
The sum variable in your code is a local variable, its scope is only at the function level. This means the sum always get initialized to 0 and increased to 1 every time the function newLecturer() is called. That's why sum always smaller than MAX_LECTURER (1<3).
You need to use class variable numLecturers like in duffymo answer above.

Why dosen't my for each loop return anything?

The purpose of my code is to have the user input the name of a car. The code will use a for loop to search through an array list and print out the car that the user typed in. The code compiles, but it doesn't print anything out. Here is the code:
public class searchList
{
private static inventory inventory = new inventory();
private static ArrayList<engineSpecs> list = inventory.getList();
public void searchList()
{
//Declarations
Scanner scan = new Scanner(System.in);
String search = new String();
String car = new String();
//Prompts user to enter car name
System.out.println ("Enter car name: ");
car = scan.nextLine();
//Searches array list and prints car
for (engineSpecs item: list)
{
if (item.equals(car))
{
System.out.println (item);
}
}
}
}
The array list is declared in another class. Here is that class:
public class inventory
{
public static ArrayList<engineSpecs> list = newArrayList<engineSpecs>();
public inventory()
{
//Adds objects into array list
engineSpecs astonmartin = new engineSpecs("Aston Martin", "Vanquish", 350000, 11, "Gray",
2015, 565, 457, "automatic");
engineSpecs ferrari = new engineSpecs ("Ferrari", "458 Italia", 240000, 13, "Red", 2015,
570, 398, "automatic");
list.add(astonmartin);
list.add(ferrari);
}
public static ArrayList<engineSpecs> getList()
{
//getter method
return list;
}
}
My engineSpecs class is just a simple constructor. I'm using it so I can instantiate an object of this constructor and save it into the array list.
public class engineSpecs
{
private int HP;
private int torque;
private String transmission;
private int year;
private int MPG;
private int price;
private String model;
private String color;
private String manufacturer;
public engineSpecs (String manufacturerName, String modelName,int stickerPrice, int MPGe,
String extColor, int yearNum, int BHP, int torquelbs, String transmissionType)
{
HP = BHP;
torque = torquelbs;
transmission = transmissionType;
year = yearNum;
MPG = MPGe;
price = stickerPrice;
model = modelName;
color = extColor;
manufacturer = manufacturerName;
}
public String toString()
{
String result = "Manufacturer: " + manufacturer + "\n";
result += "Model: " + model + "\n";
result += "Price: " + price + "\n";
result += "Estimated MPG: " + MPG + "\n";
result += "Color: " + color + "\n";
result += "Year: " + year + "\n";
result += "Horse power: " + HP + "\n";
result += "Torque: " + torque + "\n";
result += "Transmission: " + transmission + "\n";
return result;
}
}
Your are using .equals() for objects which is not going to return true until they are same object in the memory. You need a new method that compares the string value of the name. Also you need toString() method to print the string conversion of the object.
Your engineSpecs class should look something like this:
public class engineSpecs{
public String name;
public engineSpecs(String s){
this.name = s;
}
public boolean is(String car){
return this.name.equals(car);
}
public String toString(){
return this.name;
}
}
Update:
change your if statement to :
if (item.is(car))
{
System.out.println (item);
}
Define this method in engineSpecs :
public boolean is(String manufacturerName){
return this.manufacturer.equals(manufacturerName);
// need to compare more values if you want to compare more properties
}
You can try to redefine the method equals() in your class engineSpecs, so the line item.equals(car) works correctly.
More info here.

something wrong with the calculateWeeklypay methods of each employees

well i have now four types of employees. Managers (who receive a fixed weekly salary), Design workers (who receive a fixed hourly wage for up to the first 40 hours they work and "time-and-a-half," i.e., 1.5 times their hourly wage, for overtime hours worked), Sales workers (who receive a $250 plus 5.7% of their gross weekly sales), and Manufacturing (who receive a fixed amount of money per item for each of the items they produce -- each manufacture in this company works on only one type of item). and here are my classes:
employee class
the problem is i get this output:
You chose to open this file: Employees.txt
John Smith Manufacturing 6.75 120 444
0.0
Betty White Manager 1200.0 0 111
0.0
Stan Slimy Sales 10000.0 0 332
250.0
Betty Boop Design 12.5 50 244
0.0
meaning that it is getting 0 for all my calculations and leading to this weekly report:
WEEKLY PAY REPORT FOR Wacky Widgets COMPANY
Employee
0
WEEKLY PAY
250
Total Payroll: $0.0
Total number of managers paid:1
Total number of Design Employees paid:1
Total number of Sales Employees paid:1
Total number of Manufacturing Employees paid:1
i need help with fixing my methods so they can accept the integers of the file and use them in the calculation since all i'm getting at the moment are 0 values. i can provide my read-file method if it is need . thanks
here is the abstract class from which all the other employees type are extending from
[code]
public abstract class Employee {
public abstract double calculateWeeklyPay();
private String fName;
private String lName;
private int EmpId;
private Position p;
/*
public Employee()
{
}*/
/**
* default constructor
*/
public Employee() {
// TODO Auto-generated constructor stub
/*this.getFName();
this.getLName();
this.getEmpId();*/
getFName();
getLName();
this.getEmpId();
}
/**
* #param string first name
* #param string2 last name
* #param y position
*/
public Employee(String string, String string2, String y) {
fName = string;
lName = string2;
// EmpId=string3;
if (y.equals("Design")) {
p = Position.Design;
}
if (y.equals("Sales")) {
p = Position.Sales;
}
if (y.equals("Manufacturing")) {
p = Position.Manufacturing;
}
if (y.equals("Manager")) {
p = Position.Manager;
}
// StringTokenizer str=new StringTokenizer(fName+ lName+y,": .");
}
/**
* #return first name
*/
public String getFName() {
return fName;
}
/**
* #param firstName sets the first name
*/
public void setFName(String firstName) {
this.fName = firstName;
}
/**
* #return last name
*/
public String getLName() {
return lName;
}
/**
* #param lastName
*/
public void setLName(String lastName) {
this.lName = lastName;
}
/*public String toString()
{
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return firstName;
}*/
/**
* #return p position
*/
public Position getPosition() {
// String str = firstName+" "+lastName+" "+"Position: "+getPosition();
return p;
}
public String toString() {
String str = fName + " " + lName + " " + "Position: " + getPosition();
return str;
}//https://www.udemy.com/blog/java-abstract-class/
public int getEmpId() {
return EmpId;
}
public void setEmpId(int empId) {
this.EmpId = empId;
}
}
design employee class
public class Design extends Employee {
public double rate;//rate for each hours
public double h;//hours worked
public Design(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
//double firstParam, int secondParam, int empNum
super(fName, lName, pos);
//toString();
calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weeklyPay = 0;
if (h <= 40) {
weeklyPay = h * rate;
}
if (h > 40) {
h = h * (3 / 2);
weeklyPay = h * rate;
}
//System.out.println(weeklyPay);
return weeklyPay;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
}
sales employee
public class Sales extends Employee {
private double weekSales;
private final double pay = 250;
private final double percent = .057;
public Sales(String fName, String lName, String pos) {
// TODO Auto-generated constructor stub
super(fName, lName, pos);
this.calculateWeeklyPay();
}
#Override
public double calculateWeeklyPay() {
// TODO Auto-generated method stub
double weekPay;
weekPay = pay + percent * this.getWeekSales();
return weekPay;
}
public double getWeekSales() {
return weekSales;
}
public void setWeekSales(double weekSales) {
this.weekSales = weekSales;
}
}
and i have two other employee type of classes but they won't be needed here since if i fix the problem in this one class i can fix the others.
here's is my company class which reads a file a calculates the weekly pay and total weekly pay of all employees classes
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Company implements CompanyInterface {
//private Employee addEmp = new Employee();
// private Position addPosition = new
private ArrayList<Employee> list;
private static int numberOfCompanies;
private String CompanyName;
private int numDesign;
private int numEmployees;
private int numManufacturing;
private int numManager;
private int numSales;
/*String fName="";
String lName="";
String position="";
String first="";
String second="";
String empID="";
Scanner File;*/
//private ArrayList<Employee> list2 ;
private Employee addEmp;
/**
* #param cn is the company name
*/
public Company(String cn) {
cn = "Wacky Widgets";
list = new ArrayList<Employee>();
numDesign = 0;
numEmployees = 0;
numManufacturing = 0;
numSales = 0;
numberOfCompanies++;
setCompanyName(cn);
}
#Override
/**
* #param fName first name
* #param lName last name
* #param pos position
* #return null if everything is right
*/
public String addEmployee(String fName, String lName, String pos,
double firstParam, int secondParam, int empNum) {
String message = null;
// if (pos.equals("DESIGN")&&
numDesign == 1 && numSales != 2 && numManufacturing != 4)
if (pos.equals("Design")) {
if (numDesign == 2)//p2=Position.DESIGN;
{
message = "There are already 2 design persons\nEmployee not
added ";
} else {
addEmp = new Design(fName, lName, pos);
numDesign++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
//if (pos.equals("SALES")&&numDesign<1&&numSales<2&&numManufacturing<4)
else if (pos.equals("Sales")) {
if (numSales == 1) {
message = "There is already a sales person\nEmployee not
added ";
} else {
//p2=Position.SALES;
addEmp = new Sales(fName, lName, pos);
numSales++;
numEmployees++;
list.add(addEmp);
}
}//else return message;
else if (pos.equals("Manufacturing")) {
if (numManufacturing == 4) {
message = "There are already four manufacturing persons
\nEmployee not added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManufacturing++;
numEmployees++;
list.add(addEmp);
}
} else if (pos.equals("Manager")) {
if (numManager == 1) {
message = "There is already a manager person\nEmployee not
added ";
} else {
//p2=Position.MANUFACTURING;
addEmp = new Manufacturing(fName, lName, pos);
numManager++;
numEmployees++;
list.add(addEmp);
}
}
//String str=fName+" "+lName+" "+pos+" "+firstParam+" "+empNum;
System.out.println(fName + " " + lName + " " + pos + " " + firstParam + " " + secondParam + "
"+empNum);
//firstParam=Employee.
System.out.println(calculateTotalWeeklyPay());
return message;
}
/**
* Returns number of companies
*
* #return number of companies
*/
public static int getNumCompanies() {
return numberOfCompanies;
}
public void setNumCompanies(int nc) {
numberOfCompanies = nc;
}
/**
* Sets the number of employees
*
* #param ne number of employees
*/
public void setNumemployees(int ne) {
numEmployees = ne;
}
/**
* Returns the number of employees
*
* #return the number of employees
*/
public int getNumEmployees() {
return numEmployees;
}
#Override
public int getNumManager() {
return numManager;
}
/**
* sets the number of designer
*
* #param nd number of designer
*/
public void setNumDesign(int num) {
numDesign = num;
}
#Override
public int getNumDesign() {
return numDesign;
}
public void setNumsales(int num) {
numSales = num;
}
#Override
public int getNumSales() {
return numSales;
}
/**
* Sets the number of manufacturer
*
* #param nm the number of manufacturer
*/
public void setNumManufacturing(int num) {
numManufacturing = num;
}
#Override
public int getNumManufacturing() {
return numManufacturing;
}
public void setNumManager(int num) {
numManager = num;
}
#Override
public String generateWeeklyReport() {
int empID = 0;
String title = "WEEKLY PAY REPORT FOR " + getCompanyName() + " COMPANY" + "\n";
String label = "Employee\n";
String label2 = "WEEKLY PAY \n";
int payWeek = 0;
double total = 0.0;
for (Employee index : list) {
empID += index.getEmpId();
payWeek += index.calculateWeeklyPay();
}
return title + label + empID + "\n" + "\t" + label2 + payWeek + "\n" + "Total Payroll:
$ "+total+"\n "+
"Total number of managers paid:" + getNumManager() + "\n" +
"Total number of Design Employees paid:" + getNumDesign() + "\n" +
"Total number of Sales Employees paid:" + getNumSales() + "\n" +
"Total number of Manufacturing Employees paid:" + getNumManufacturing();
}
#Override
public double calculateTotalWeeklyPay() {
double total = 0;
for (int index = 0; index < list.size(); index++) {
total = list.get(index).calculateWeeklyPay();
//total.add(list.get(index).calculateWeeklyPay());
}
return total;
}
/**
* #return str the arraylist of employees and positions
*/
public String printCompany() {
// TODO Auto-generated method stub
String str = "";
for (int index = 0; index < list.size(); index++) {
str += list.get(index).getFName() + " " + list.get(index).getLName() + "
"+" Position:
"+list.get(index).getPosition()+"\n ";
}//System.out.println(str);
return str;
}
/**
* #return company name
*/
public String getCompanyName() {
return CompanyName;
}
public void setCompanyName(String companyName) {
//companyName="Wacky Widgets";
this.CompanyName = companyName;
}
public String toString() {
// int i =0;
String str = CompanyName + "";
//String str = "";
for (int i = 0; i < list.size(); i++) {
str += "\n" + list.get(i).getFName() + " " + list.get(i).getLName() + "
"+" Position:
"+list.get(i).getPosition()+"\n ";
}
return str;
}
}
This stands out:
h = h * (3 / 2);
You're doing integer division here, so you're always multiplying by 1, effectively.
Change that to use floating-point values instead.
h = h * (3.0 / 2);
Alternatively, be explicit about what you're multiplying by - you know it's always time and a half, so I see no reason not to do this:
h = h * 1.5;

How do read from a .txt file and put data into an array list of an object?

What I have written so far works from my current knowledge of basic arrays, but I just don't understand how to use an arraylist, or how to read from a file. What I have written so far works. Any links or advice to help fix my code to read from a file and use an arraylist would be greatly appreciated. Thank you.
public class TestPackages
{
public static void main (String[] args)
{
Packages testPackages = new Packages();
testPackages.addPacket(1001, 7.37, "CA");
testPackages.addPacket(1002, 5.17, "CT");
testPackages.addPacket(1003, 11.35, "NY");
testPackages.addPacket(1004, 20.17, "MA" );
testPackages.addPacket(1005, 9.99, "FL");
testPackages.addPacket(1006, 14.91, "VT");
testPackages.addPacket(1007, 4.97, "TX");
System.out.println(testPackages);
}
}
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Packages
{
private Packet[] shipment;
private int count;
private double totalWeight;
public Packages()
{
shipment = new Packet[100];
count = 0;
totalWeight = 0.0;
}
public void addPacket (int idNumber, double weight, String state)
{
if(count == shipment.length)
increaseSize();
shipment[count] = new Packet (idNumber, weight, state);
totalWeight += weight;
count++;
}
public String toString()
{
String report;
report = "All Packets\n";
for(int num = 0; num < count; num++)
report += shipment[num].toString() + "\n";
report += "Total Weight:\t" +totalWeight+" pounds";
return report;
}
private void increaseSize()
{
Packet[] temp = new Packet[shipment.length * 2];
for (int num = 0; num < shipment.length; num++)
temp[num] = shipment[num];
shipment = temp;
}
}
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
public class Packet
{
private int idNumber;
private double weight;
private String state;
public Packet(int idNumber, double weight, String state)
{
this.idNumber = idNumber;
this.weight = weight;
this.state = state;
}
public boolean isHeavy(double weight)
{
return (weight > 10);
}
public boolean isLight(double weight)
{
return (weight < 7);
}
public String toString()
{
String description = "ID number: " + idNumber + "\tWegiht: " + weight + "\tState: "
+ state;
return description;
}
}
Try this link to learn how to read from file with JAVA
How to read a large text file line by line using Java?
You can try the following code to learn how to use Arraylist (There are many more tutorials in the web)
Packet p1=new Packet (1001, 7.37, "CA");
Packet p2=new Packet (1002, 17.5, "SF");
Packet p3=new Packet (1003, 13.8, "DF");
Packet p4=new Packet (1004, 14.4, "XC");
ArrayList<Packet> arr= new ArrayList<Packet>();
arr.add(p1);
arr.add(p2);
arr.add(p3);
arr.add(1,p4);
System.out.println("return the 2st element- " + arr.get(1) );
System.out.println("return the 4rd element- " + arr.get(3) );
System.out.println("Size of ArrayList after insertion- " + arr.size());
System.out.println("Elements of ArrayList after insertion- " + arr);
arr.remove(p2);
arr.remove(2);
System.out.println("Size of ArrayList after deletion- " + arr.size());
System.out.println("Elements of ArrayList after deletion- " + arr);
There are many ways to read a file line by line in java. But I prefer using commons-io utils. It's a very useful tool that provide reading from a file. Here is a one line example.
List<String> lines = FileUtils.readLines(new File(fileName));

Categories

Resources