how to read data from arraylist that is inside linkedlist - java

I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
StringTokenizer st = new StringTokenizer(str2,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct1 = new Indicator (cCode,iName,iCode,data);
bigdata.insertAtBack(idct1);
str2 = br2.readLine();
}
//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(bigdata,search3);
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
public static void searchYear (myLinkedList bigdata, int searchTerm) {
Indicator idct4 = (Indicator)bigdata.getFirst();
boolean found = false;
while(idct4 != null){
if(idct4.getDYear() == searchTerm) {
found = true;
System.out.println(idct4.getDValue());
}
idct4 = (Indicator)bigdata.getNext();
}
if (!found){
String message = "Error!";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
}
}
indicator class:
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
public String getCCode(){return cCode;}
public String getIName(){return iName;}
public String getICode(){return iCode;}
public int getDYear(){return d.getYear();}
public String getDValue(){return d.getValue();}
public void setCCode(String cCode){this.cCode = cCode;}
public void setIName(String iName){this.iName = iName;}
public void setICode(String iCode){this.iCode = iCode;}
public String toString(){
return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
}
}
MyData class:
public MyData(int year, String value){
this.year = year;
this.value = value;
}
public int getYear(){return year;}
public String getValue(){return value;}
public void setYear(int year){this.year = year;}
public void setValue(String value){this.value = value;}
public String toString(){
return (value + "(" + year + ")");
}

I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(idct3,search3); // Indicator passed in here
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
for (int i = 0; i < indicator.DataList.size(); i++) {
if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() + " having value " + indicator.DataList.get(i).getValue());
return; // Exit this method
}
}
System.out.println("Not Found");
}

Related

How to use array of objects in this context?

Assuming that the array is populated with 20 shipments, calculate the total cost of local shipments in the array.
I tried to create a for loop and then call out the method calcCost() and += it to the variable local so it would save the values I guess
I'm pretty sure the way I wrote the code is wrong so if someone could help me with it that would be great!
package question;
public class TestShipment {
public static void main(String[] args) {
Shipment r1 = new Shipment(
new Parcel("scientific calculator " , 250),
new Address("Dubai","05512345678"),
new Address("Dubai","0505432123"),
"Salim"
);
System.out.println(r1);
Shipment[] arr = new Shipment[100];
arr[5] = r1;
Shipment[] a = new Shipment[20];
double local = 0;
for (int i = 0; i < a.length; i++) {
if (a[i].isLocalShipment()) {
System.out.println(a[i].calcCost());
}
}
}
}
public class Shipment {
public Parcel item;
private Address fromAddress;
private Address toAddress;
public String senderName;
public Shipment(Parcel i, Address f, Address t, String name) {
item = i;
fromAddress = f;
toAddress = t;
senderName = name;
}
//setter
public void setFromAddress(String c, String p) {
c = fromAddress.getCity();
p = fromAddress.getPhone();
}
public boolean isLocalShipment() {
boolean v = false;
if (fromAddress.getCity() == toAddress.getCity()) {
v = true;
} else {
v = false;
}
return v;
}
public double calcCost() {
double cost = 0;
if (fromAddress.getCity() == toAddress.getCity()) {
cost = 5;
} else {
cost = 15;
}
if(item.weight > 0 && item.weight <= 200) {
cost += 5.5;
}
if(item.weight > 200) {
cost += 10.5;
}
return cost = cost * (1 + 0.5); //fix the tax
}
public String toString() {
return "From: " + senderName + "\nTo: " + toAddress
+ "\nParcel: " + item.desc+item.weight + "\ncost: " + calcCost();
}
}

How to search an array for a value?

I cant get case 3 and 4 to work correctly. I don't have an error but correct information is not displaying. For case 3, it displays the last item in the array even if another is entered.4 is not displaying.
These are the directions
The Video class should also have a static method called listVideosStarring that finds all movies that have
a particular star in them. This method takes a parameter that is the star’s name, and loop through the array
of products and concatenate the names of all the videos in the array that have the specified star in them.
Beware that not all the elements of this array point to Video instances; therefore, you will need to make
sure that a reference points to a Video instance before attempting to obtain the star. Also, since the Products
array is of type Product, you will need to treat the element as if it points to a Video to obtain the star's
name (this requires typecasting). Also keep in mind that because the member variable may contain more
than one star, you cannot assume that it necessarily equals the string entered by the user; instead you need
to see if the user’s entry is contained somewhere within the star member variable’s value.
Video and Automobile are subclasses of Product and products is the array
public class ProductsApplication {
public static void main (String [] args){
menuChoice();}
//method for menu choices
public static void menuChoice (){
boolean loopContinue = true;
while (loopContinue){
Scanner scan = new Scanner(System.in);
System.out.println("Choices are: ");
System.out.println("(1) Read products file");
System.out.println("(2) List products and show total inventory value");
System.out.println("(3) Display information about a product");
System.out.println("(4) List products with a given star");
System.out.println("(5) Show graph of inventory values");
System.out.println("(6) Quit");
System.out.println("What is your choice? (1-6)");
try {
String selection = scan.nextLine();
switch(selection)
{
case "1":
try{
//Create file
File inputFile = new File("C:/Users/Olivia/Desktop/CIS331/products.txt");
Scanner scanner = new Scanner(inputFile);
//read data from file
for (int i= 0; i< Product.MAXPRODUCTS; i++)
{
while(scanner.hasNext()){
String type = scanner.nextLine();
if (type.equals("PRODUCT")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
boolean add = Product.addProduct(pName, pDescription, pQuantity, pPrice);
}
if (type.equals("AUTOMOBILE")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
int y = Integer.parseInt(scanner.nextLine());
String mm = scanner.nextLine();
boolean add = Automobile.addAutomobile(pName, pDescription, pQuantity, pPrice, y, mm);
}
if(type.equals("VIDEO")){
String pName= scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
String genere = scanner.nextLine();
String rate = scanner.nextLine();
int time = Integer.parseInt(scanner.nextLine());
String star = scanner.nextLine();
boolean add= Video.addVideo(pName, pDescription, pQuantity, pPrice, genere, rate, time, star);
}
}
}
System.out.println("File read successfully");
}
catch (FileNotFoundException e) {
System.out.println("Error reading" + e.toString());
}
break;
case "2":
System.out.println("List of products:");
System.out.println(Product.listProducts());
break;
case "3":
System.out.print("Enter the name of the product: ");
String findName = scan.nextLine();
int index = Product.findProduct(findName);
if (index >=0){
Product product = Product.getProduct(index);
System.out.println(product.prodInfo(true));}
else
{
System.out.println("Product was not found");
}
break;
case "4":
System.out.println("Enter the name of the star to search: ");
String starName = scan.nextLine();
System.out.println("Videos starring " + starName);
System.out.println(Video.listVideoStarring(starName));
break;
case "5":
break;
case "6":
System.exit(0);
break;
default:
System.out.println("error please try again");
break;
}
}
public class Product {
//instance member variables of the class
String productName;
private String productDescription;
private int productQuantity;
private double unitPrice;
//static member variables
protected static final int MAXPRODUCTS = 10;
protected static Product [] products;
protected static int totProducts =0;
//default constructor
public Product(){
this.productName = "PRODUCT";
this.productDescription = "DESCRIPTION";
this.productQuantity = 0;
this.unitPrice = 0.0 ;
}
//overloaded constructor
public Product(String name, String description, int quantity, double price){
setproductName(name);
setproductDescription(description);
setproductQuantity(quantity);
setunitPrice(price);
}
//getters and setters for instance varibles
public void setproductName(String name){
String firstLetter = name.substring(0,1).toUpperCase();
String nameCapitalized = firstLetter + name.substring(1). toLowerCase();
this.productName = nameCapitalized;
}
public String getproductName (){
return productName;
}
public void setproductDescription( String description){
this.productDescription = description;
}
public String getproductDescription(){
return productDescription;
}
public void setproductQuantity(int quantity){
if (quantity < 0){
this.productQuantity = 0;
}
else {
this.productQuantity = quantity;
}
}
public int getproductQuantity(){
return productQuantity;
}
public void setunitPrice (double price){
if (price<0){
this.unitPrice = 0.00;
}
else{
this.unitPrice = price;}
}
public double getunitPrice(){
return unitPrice;
}
//Methods
//Method for product information of a product instance
public String prodInfo(boolean booleanVariable){
if (booleanVariable){
NumberFormat numberFormat=NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getproductName() + System.lineSeparator()
+ "Product Description: " + getproductDescription() + System.lineSeparator()
+ "Product Quantity: " + getproductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getunitPrice()) + System.lineSeparator()
+ "Total value: " + numberFormat.format(totalValue());}
else {
return getproductName();
}
}
//Method that returns the total value of the product, quantity times price
public double totalValue(){
return (this.productQuantity * this.unitPrice);
}
/*Method that takes string parameters and tests to see if that parameters value
is equal to the value of products name, returns boolean*/
public boolean testsValue(String testString){
return this.getproductName().equalsIgnoreCase(productName);
}
//list names in the product array
public static String listProducts(){
StringBuilder s= new StringBuilder();
StringBuilder s2 = new StringBuilder();
if(products!= null && totProducts>0){
for(int i=0; i<totProducts; i++){
s.append(products[i].toString());
s.append(" ");
s.append(products[i].productName+"\n");
}
}
else{
s.append("No products available.");
}
return s.toString();
}
//find product in an array
public static int findProduct (String findName){
int index = -1;
if(products!=null && totProducts>0){
for( int i=0; i<totProducts; i++){
if(products[i].testsValue(findName))
{
index = i;
}
else {
index = -1;
return index;
}
}
}
return index;
}
//add product to array
public static boolean addProduct(String pName, String pDescription, int pQuantity, double pPrice){
if(totProducts== MAXPRODUCTS)
{
return false;
}
if(products == null){
products= new Product[MAXPRODUCTS];
}
Product newProduct = new Product(pName, pDescription, pQuantity, pPrice);
products[totProducts]= newProduct;
totProducts++;
return true;
}
// calculate total value of inventory in stock
public static double totInventoryValue(){
double sum = 0;
if (products != null && totProducts>0){
for(int i=0; i<totProducts; i++){
sum+= products[i].totalValue();
}
}
return sum;
}
//get accessor method for obtaining particular product from the index
public static Product getProduct(int index){
Product product= null;
if(products!= null && totProducts>0 && index>=0 && index<totProducts){
product = products[index];
}
return product;
}
// method added
public String toString(){
return "Product";
}
}
public class Video extends Product{
//instance member variables
private String movieType;
private String rating;
private int runningTime;
private String actors;
//default constructor
public Video(){
super();
this.movieType = "comedy";
this.rating ="Not Rated";
this.runningTime = 0;
this.actors ="Unknown";
}
//Overloaded constructor
public Video(String productName, String productDescription, int productQuantity, double unitPrice,
String movieType, String rating, int runningTime, String actors){
super(productName, productDescription, productQuantity, unitPrice);
setmovieType(movieType);
setrating(rating);
setrunningTime(runningTime);
setactors(actors);
}
//setters and getters
public void setmovieType(String movieType){
if(movieType.equals("comedy") || movieType.equals("drama") || movieType.equals("action")
|| movieType.equals("documentary")){
this.movieType = movieType;
}
else{
this.movieType = "comedy";
}
}
public String getmovieType(){
return movieType;
}
public void setrating(String rating){
if( rating.equals("G") || rating.equals("PG") || rating.equals("PG-13") || rating.equals("R")
|| rating.equals("Not Rated")){
this.rating = rating;
}
else{
this.rating = "Not Rated";
}
}
public String getrating(){
return rating;
}
public void setrunningTime(int runningTime){
if (runningTime < 30){
this.runningTime = 30;
}
if (runningTime > 500){
this.runningTime = 500;
}
else{
this.runningTime = runningTime;
}
}
public int getrunningTime(){
return runningTime;
}
public void setactors(String actors){
this.actors = actors;
}
public String getactors(){
return actors;
}
// to string that overrides product class
public String toString(){
return "Video";
}
// add video, creating instance
public static boolean addVideo(String productName, String productDescription, int productQuantity, double unitPrice,
String movieType, String rating, int runningTime, String star){
if(totProducts == MAXPRODUCTS)
{
return false;
}
if (products == null){
products= new Product[MAXPRODUCTS];
}
Video newVideo = new Video(productName, productDescription, productQuantity, unitPrice, movieType, rating,
runningTime, star);
Product.products[Product.totProducts]= newVideo;
Product.totProducts++;
return true;
}
//override prod info
public String prodInfo(boolean booleanVariable){
if (booleanVariable){
NumberFormat numberFormat=NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getproductName() + System.lineSeparator()
+ "Product Description: " + getproductDescription() + System.lineSeparator()
+ "Product Quantity: " + getproductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getunitPrice()) + System.lineSeparator()
+ "Total value: " + numberFormat.format(totalValue()) + System.lineSeparator() + "Movie Type: " + getmovieType() + System.lineSeparator()
+ "Running Time: " + getrunningTime() + System.lineSeparator() + "Rating: " + getrating() + System.lineSeparator()
+ "Stars: " + getactors() ;}
else {
return getproductName();
}
}
//new method to find movies that a star is in a movie
public static String listVideoStarring(String starName){
StringBuilder sb = new StringBuilder();
for (int i= 0; i<totProducts; i++){
if (((Video)products[i]).contains(starName)){
sb.append(((Video)products[i]).productName.toString());
}
}
return sb.toString();
}
}
`
This is the text file I read in
PRODUCT
Generic product
This is the description for product 1.
15000
12.50
VIDEO
Shrek
Animated movie about an ogre, a princess, and a donkey.
25000
15.25
comedy
PG
120
Mike Myers, Eddie Murphy, Cameron Diaz
AUTOMOBILE
Fancy car
A very cool and fast red sports car.
12
33999.99
2020
Ford Mustang
VIDEO
Goldmember
Hijinks of a British spy.
13000
8.45
comedy
PG-13
90
Mike Myers, Mindy Sterling, Michael Caine, Seth Greene, Heather Graham
AUTOMOBILE
Eco-friendly car
Better for the environment.
18
27999.99
2020
Toyota Prius
VIDEO
Black Panther
A Marvel Comics superhero movie
14000
13.75
drama
PG-13
90
Chadwick Boseman, Lupita Nyong'o, Michael B. Jordan
Ideally, class Product should be abstract. You can't really create a "product" but you can create a video and you can create an automobile. However, from your code it appears that you can create a "generic" Product so in your circumstances, class Product should not be made abstract.
Default constructors don't make sense because a productName should be used to identify a Product object and therefore each Product object should have a unique productName. I would remove the default constructors.
Your identifiers do not strictly adhere to Java naming conventions. In the below code I have made the relevant changes.
In method findProduct(), of class Product, remove the else. You are only testing the first element in the array products. I assume that each Product must have a unique productName and therefore the method should be:
public static int findProduct(String findName) {
int index = -1;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
if (products[i].testsValue(findName)) {
index = i;
break;
}
}
}
return index;
}
You should add another addProduct() [static] method to class Product with a single Product argument. Then you can add Video objects and Automobile objects to products array.
public static boolean addProduct(Product newProduct) {
if (products == null) {
products = new Product[MAXPRODUCTS];
totProducts = 0;
}
boolean added = false;
if (newProduct != null && totProducts < MAXPRODUCTS) {
products[totProducts] = newProduct;
totProducts++;
added = true;
}
return added;
}
Consequently, you can change your existing addProduct() method.
public static boolean addProduct(String pName,
String pDescription,
int pQuantity,
double pPrice) {
return addProduct(new Product(pName, pDescription, pQuantity, pPrice));
}
When reading the products.txt file, you should use try-with-resources to make sure that the file gets closed. Also, the for loop is not required. You should change the while loop so that it stops reading the file after totProducts equals MAXPRODUCTS.
You should almost always print the stack trace of exceptions rather than just print the error message as this will help you to locate the code that is causing the error.
Method testsValue(), in class Product is also wrong. You should check the parameter value.
public boolean testsValue(String testString) {
return this.getProductName().equalsIgnoreCase(testString);
}
Finally, you need to change method listVideoStarring(), in class Video.
public static String listVideoStarring(String starName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totProducts; i++) {
if (products[i] instanceof Video) {
Video video = (Video) products[i];
if (video.getActors().contains(starName)) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(video.getProductName());
}
}
}
return sb.toString();
}
Here is complete code.
Class Video
import java.text.NumberFormat;
import java.util.Locale;
public class Video extends Product {
// instance member variables
private String movieType;
private String rating;
private int runningTime;
private String actors;
// Overloaded constructor
public Video(String productName,
String productDescription,
int productQuantity,
double unitPrice,
String movieType,
String rating,
int runningTime,
String actors) {
super(productName, productDescription, productQuantity, unitPrice);
setMovieType(movieType);
setRating(rating);
setRunningTime(runningTime);
setActors(actors);
}
// setters and getters
public void setMovieType(String movieType) {
if (movieType.equals("comedy") || movieType.equals("drama") || movieType.equals("action")
|| movieType.equals("documentary")) {
this.movieType = movieType;
}
else {
this.movieType = "comedy";
}
}
public String getMovieType() {
return movieType;
}
public void setRating(String rating) {
if (rating.equals("G") || rating.equals("PG") || rating.equals("PG-13")
|| rating.equals("R") || rating.equals("Not Rated")) {
this.rating = rating;
}
else {
this.rating = "Not Rated";
}
}
public String getRating() {
return rating;
}
public void setRunningTime(int runningTime) {
if (runningTime < 30) {
this.runningTime = 30;
}
if (runningTime > 500) {
this.runningTime = 500;
}
else {
this.runningTime = runningTime;
}
}
public int getRunningTime() {
return runningTime;
}
public void setActors(String actors) {
this.actors = actors;
}
public String getActors() {
return actors;
}
// to string that overrides product class
public String toString() {
return "Video";
}
// add video, creating instance
public static boolean addVideo(String productName, String productDescription,
int productQuantity, double unitPrice, String movieType, String rating, int runningTime,
String star) {
if (totProducts == MAXPRODUCTS) {
return false;
}
if (products == null) {
products = new Product[MAXPRODUCTS];
}
Video newVideo = new Video(productName, productDescription, productQuantity, unitPrice,
movieType, rating, runningTime, star);
Product.products[Product.totProducts] = newVideo;
Product.totProducts++;
return true;
}
// override prod info
public String prodInfo(boolean booleanVariable) {
if (booleanVariable) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getProductName() + System.lineSeparator()
+ "Product Description: " + getProductDescription() + System.lineSeparator()
+ "Product Quantity: " + getProductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getUnitPrice())
+ System.lineSeparator() + "Total value: " + numberFormat.format(totalValue())
+ System.lineSeparator() + "Movie Type: " + getMovieType()
+ System.lineSeparator() + "Running Time: " + getRunningTime()
+ System.lineSeparator() + "Rating: " + getRating() + System.lineSeparator()
+ "Stars: " + getActors();
}
else {
return getProductName();
}
}
// new method to find movies that a star is in a movie
public static String listVideoStarring(String starName) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totProducts; i++) {
if (products[i] instanceof Video) {
Video video = (Video) products[i];
if (video.getActors().contains(starName)) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(video.getProductName());
}
}
}
return sb.toString();
}
}
Class Product
import java.text.NumberFormat;
import java.util.Locale;
public class Product {
// instance member variables of the class
String productName;
private String productDescription;
private int productQuantity;
private double unitPrice;
// static member variables
protected static final int MAXPRODUCTS = 10;
protected static Product[] products;
protected static int totProducts = 0;
// overloaded constructor
public Product(String name, String description, int quantity, double price) {
setProductName(name);
setProductDescription(description);
setProductQuantity(quantity);
setUnitPrice(price);
}
// getters and setters for instance varibles
public void setProductName(String name) {
String firstLetter = name.substring(0, 1).toUpperCase();
String nameCapitalized = firstLetter + name.substring(1).toLowerCase();
this.productName = nameCapitalized;
}
public String getProductName() {
return productName;
}
public void setProductDescription(String description) {
this.productDescription = description;
}
public String getProductDescription() {
return productDescription;
}
public void setProductQuantity(int quantity) {
if (quantity < 0) {
this.productQuantity = 0;
}
else {
this.productQuantity = quantity;
}
}
public int getProductQuantity() {
return productQuantity;
}
public void setUnitPrice(double price) {
if (price < 0) {
this.unitPrice = 0.00;
}
else {
this.unitPrice = price;
}
}
public double getUnitPrice() {
return unitPrice;
}
// Methods
// Method for product information of a product instance
public String prodInfo(boolean booleanVariable) {
if (booleanVariable) {
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
return "Product Name: " + getProductName() + System.lineSeparator()
+ "Product Description: " + getProductDescription() + System.lineSeparator()
+ "Product Quantity: " + getProductQuantity() + System.lineSeparator()
+ "Product Price: " + numberFormat.format(getUnitPrice())
+ System.lineSeparator() + "Total value: " + numberFormat.format(totalValue());
}
else {
return getProductName();
}
}
// Method that returns the total value of the product, quantity times price
public double totalValue() {
return (this.productQuantity * this.unitPrice);
}
/*
* Method that takes string parameters and tests to see if that parameters value
* is equal to the value of products name, returns boolean
*/
public boolean testsValue(String testString) {
return this.getProductName().equalsIgnoreCase(testString);
}
// list names in the product array
public static String listProducts() {
StringBuilder s = new StringBuilder();
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
s.append(products[i].toString());
s.append(" ");
s.append(products[i].productName + "\n");
}
}
else {
s.append("No products available.");
}
return s.toString();
}
// find product in an array
public static int findProduct(String findName) {
int index = -1;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
if (products[i].testsValue(findName)) {
index = i;
break;
}
}
}
return index;
}
// add product to array
public static boolean addProduct(String pName,
String pDescription,
int pQuantity,
double pPrice) {
return addProduct(new Product(pName, pDescription, pQuantity, pPrice));
}
public static boolean addProduct(Product newProduct) {
if (products == null) {
products = new Product[MAXPRODUCTS];
totProducts = 0;
}
boolean added = false;
if (newProduct != null && totProducts < MAXPRODUCTS) {
products[totProducts] = newProduct;
totProducts++;
added = true;
}
return added;
}
// calculate total value of inventory in stock
public static double totInventoryValue() {
double sum = 0;
if (products != null && totProducts > 0) {
for (int i = 0; i < totProducts; i++) {
sum += products[i].totalValue();
}
}
return sum;
}
// get accessor method for obtaining particular product from the index
public static Product getProduct(int index) {
Product product = null;
if (products != null && totProducts > 0 && index >= 0 && index < totProducts) {
product = products[index];
}
return product;
}
// method added
public String toString() {
return "Product";
}
}
Class ProductsApplication
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ProductsApplication {
public static void main(String[] args) {
menuChoice();
}
// method for menu choices
public static void menuChoice() {
boolean loopContinue = true;
while (loopContinue) {
Scanner scan = new Scanner(System.in);
System.out.println("Choices are: ");
System.out.println("(1) Read products file");
System.out.println("(2) List products and show total inventory value");
System.out.println("(3) Display information about a product");
System.out.println("(4) List products with a given star");
System.out.println("(5) Show graph of inventory values");
System.out.println("(6) Quit");
System.out.println("What is your choice? (1-6)");
try {
String selection = scan.nextLine();
switch (selection) {
case "1":
// Create file
File inputFile = new File("C:/Users/Olivia/Desktop/CIS331products.txt");
try (Scanner scanner = new Scanner(inputFile)) {
// read data from file
while (scanner.hasNextLine()
&& Product.totProducts < Product.MAXPRODUCTS) {
String type = scanner.nextLine();
if (type.equals("PRODUCT")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
boolean add = Product.addProduct(pName,
pDescription,
pQuantity,
pPrice);
}
if (type.equals("AUTOMOBILE")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
int y = Integer.parseInt(scanner.nextLine());
String mm = scanner.nextLine();
boolean add = Product.addProduct(new Automobile(pName,
pDescription,
pQuantity,
pPrice,
y,
mm));
}
if (type.equals("VIDEO")) {
String pName = scanner.nextLine();
String pDescription = scanner.nextLine();
int pQuantity = Integer.parseInt(scanner.nextLine());
double pPrice = Double.parseDouble(scanner.nextLine());
String genere = scanner.nextLine();
String rate = scanner.nextLine();
int time = Integer.parseInt(scanner.nextLine());
String star = scanner.nextLine();
boolean add = Product.addProduct(new Video(pName,
pDescription,
pQuantity,
pPrice,
genere,
rate,
time,
star));
}
}
System.out.println("File read successfully");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
break;
case "2":
System.out.println("List of products:");
System.out.println(Product.listProducts());
break;
case "3":
System.out.print("Enter the name of the product: ");
String findName = scan.nextLine();
int index = Product.findProduct(findName);
if (index >= 0) {
Product product = Product.getProduct(index);
System.out.println(product.prodInfo(true));
}
else {
System.out.println("Product was not found");
}
break;
case "4":
System.out.println("Enter the name of the star to search: ");
String starName = scan.nextLine();
System.out.println("Videos starring " + starName);
System.out.println(Video.listVideoStarring(starName));
break;
case "5":
break;
case "6":
System.exit(0);
break;
default:
System.out.println("error please try again");
break;
}
}
catch (Exception x) {
x.printStackTrace();
}
}
}
}

Program will not print the statement

I have a program where i select an option to add ship, which prompts me to give an id e.g b 2. it then prompts me to enter a capacity. However, I am using a search method to prevent any repeat id's that I may enter a second time round. The program compiles, but my statement "Ship id is already in use" won't print out. Any ideas please?
Here is my code.
public int search(String id)
{
for(int index = 0; index < ships.length && ships[index] != null; ++index)
{
shipId = id;
if (ships[index].getId().equals(id))
{
return index;
}
}
//ship id not found so you can add ship
return -1;
}
public void addShip( )
{
System.out.println("Enter ship id >> ");
String id = kb.nextLine();
if(id.equals(search(id)))
{
System.out.println("Ship id already in use");
return;
}
else
{
//for(int i = 0; i < ships.length; ++i)
{
System.out.println("Enter ship capacity");
int capacity = kb.nextInt();
ships[shipCounter++] = new Ship(id, capacity);
}
}
}
Here is my ship class:
public class Ship
{
private String id;
private int capacity;
private int currentCrew; // index into the Crew array
// points to the next free space
// in the Crew array
private String status;
private Crew [ ] crew;
public Ship(String id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentCrew = 0;
crew = new Crew[capacity];
}
public Ship(String id, int capacity, String status)
{
this.id = id;
this.capacity = capacity;
this.status = "available";
this.currentCrew = 0;
crew = new Crew[capacity];
}
public void setId(String newId)
{
id = newId;
}
public void setCapacity(int newCapacity)
{
capacity = newCapacity;
}
public void setStatus(String newStatus)
{
if(status.equals("available"))
{
newStatus = "on station";
status = newStatus;
}
else if(status.equals("on station"))
{
newStatus = "maintenance";
status = newStatus;
}
else if(status.equals("station") || status.equals("maintenance"))
{
newStatus = "available";
status = newStatus;
}
else
{
System.out.println("Invalid status");
}
}
public String getId()
{
return id;
}
public String getStatus()
{
return status;
}
public int getCapacity()
{
return capacity;
}
public int getCurrentCrew()
{
return currentCrew;
}
public void addCrew()
{
//if(currentCrew < capacity)
{
//System.out.println("Enter crew id >> ");
//String id = kb.nextLine();
}
}
public String toString()
{
String sdesc =
'\n'
+ "Ship"
+ '\n'
+ "["
+ '\n'
+ " "
+ "Id: " + id
+ " capacity: " + capacity
+ " current crew: " + currentCrew
+ " status: " + status
+ '\n'
+ "]";
return sdesc;
}
}
Did you noticed this line
if(id.equals(search(id)))
id is String type, but search return type is int.
if you see in String class equals method,
if (anObject instanceof String) {
}
return false;
so its simply give false always
so the simple solution is convert that int to String.
something like
if(id.equals(search(id+"")))
If you'd like to see if you already have a ship with the id, you should check that the index exists, which is what your search method returns.
if(search(id) > 0)
{
System.out.println("Ship id already in use");
return;
}

Search Array Error

I am having an issue using netbeans with this program. The program is used to search via an array from an imported text file and the text file has several columns and rows, pertaining to several characteristics of cars (i.e. License Plate Numbers). You need to create dialog boxes to search what your looking for, for each option. The problem is at the end of the code snippet starting with one.setPlate. All of the one.set(x) is being flagged, what could be the reason?
package vehiclesearch;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.JOptionPane;
public class VehicleSearch {
private static String[] sliced;
public static void main
(String[] args) throws FileNotFoundException {String NameOfFile =
JOptionPane.showInputDialog("Where is the File Path to Import Located at?");
File textFile = new File((NameOfFile));
Scanner in = new Scanner (textFile);
//Imports the appropriate text file named "vehicles.txt"//
ArrayList <String> carsArrayList = new ArrayList <>();
while(in.hasNextLine()){
String line = in.nextLine();
carsArrayList.add(line);
}
in.close();
ArrayList<VehicleSearch> vehicleObs = new ArrayList<>();
for (int i= 0; i <carsArrayList.size(); i++){
String temp = carsArrayList.get(i);
VehicleSearch VehicleClass = new VehicleSearch ();
String[] sliced = temp.split("\\s+");
vehicleClass.setPlate(sliced[0]);
int a = Integer.parseInt(sliced[1]);
vehicleClass.setYear(a);
vehicleClass.setMfg(sliced[2]);
vehicleClass.setStyle(sliced[3]);
vehicleClass.setColor(sliced[4]);
vehicleObs.add(vehicleClass);
boolean stepTwo = true;
while(stepTwo) {
String search;
search = JOptionPane.showInputDialog("Please choose one of the following search options" + "1 Plate" + "\n" +"2 Year" + "3 Manufacturer" + "\n" + "4 Body Style"+ "\n"+ "5 Color");
int searchOption = Integer.parseInt(search);
String searchVal;
searchVal = JOptionPane.showInputDialog("Enter a value to search for" + "\n" + "All values must be exact in wording, please be careful when using Caps or check for Caps Lock");
searchDialogs(vehicleObs, searchOption, searchVal);
String c;
c = JOptionPane.showInputDialog("Type S to search | E to exit");
String b = "S";
if(c.equalsIgnoreCase(b)){
stepTwo = true;
}
else{
stepTwo= false;
}
}
}
}
public static String plateCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
if(temp.contains(search)){
as.add(list.get(i).toString());
}
}
return alFormat(as);
}
public static String yearCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String mfgCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String StyleCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String colorCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static void searchDialogs(ArrayList vehicleObs, int searchOption, String
searchVal){
if(searchOption == 1){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + plateCheck(vehicleObs, searchVal));
}//Outputs data (Plate Numbers) from the text file imported
else if(searchOption == 2){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + yearCheck(vehicleObs, searchVal));
}//Outputs data (Year) from the text file imported
else if(searchOption == 3){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + mfgCheck(vehicleObs, searchVal));
}//Outputs data (Manufacturer) from the text file imported
else if(searchOption == 4){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + styleCheck(vehicleObs, searchVal));
}//Outputs data (Style) from the text file imported
else if(searchOption == 5){
JOptionPane.showMessageDialog(null, "Your following search yielded the following
results" + "\n" + colorCheck(vehicleObs, searchVal));
}//Outputs data (Color) from the text file imported
else{
JOptionPane.showMessageDialog(null, "Sorry no results have been found");
}//will only output this message only if nothing is found,//
}
public static String alFormat(ArrayList too){
String tmpString;
String full = "";
for( Object aValue | too){
tmpString = aValue + "\n";
full = full + tmpString;
}
return null;
}
}
//Vehicle Class//
public class VehicleClass {
protected String plate;//car plate
protected int year;//car model year
protected String mfg;//manufacturer
protected String style;// car style
protected String color;//color of car
public VehicleClass(){
plate = null;
year = 0000;
style = null;
color = null;
}
public VehicleClass (String e , int r, String g, String y, String c){
plate = e;
year = r;
mfg = g;
style = y;
color = c;
}
public VehicleClass copyVehicle(VehicleClass k){
VehicleClass k1 = new VehicleClass();
k1.setPlate(k.getPlate ());
k1.setYear(k.getYear());
k1.setMfg(k.getMfg());
k1.setStyle(k.getStyle());
k1.setColor(k.getColor());
return k1;
}
public void setPlate(String e){
plate= e;
}
public void setYear(int r){
year = r;
}
public void setMfg(String g){
mfg = g;
}
public void setStyle(String y){
style = y;
}
public void setColor(String c){
color = c;
}
public String getPlate(){
return plate;
}
public int getYear(){
return year;
}
public String getMfg(){
return mfg;
}
public String getStyle(){
return style;
}
public String getColor(){
return color;
}
#Override //need this?
public String toString(){
return (plate + "\t" + year + "\t" + mfg +"\t"+ style + "\t" + color);
}
}
//Text File to import//
A3245D 2009 Ford sedan white
B3396 2011 GMC pickuup blue
S214X 2010 Toyota sedan white
TR3396 2009 BMW sedan black
XR295 2011 Honda pickuup red
Z2349A 2012 Toyota suv silver
IMAQT 2009 Honda suv blue
I did some corrections in there. Now it is working. I checked with plate. Can you check it. I think code can be improved further.
VehicleSearch.java
public class VehicleSearch {
private static String[] sliced;
public static void main(String[] args) throws FileNotFoundException {
String NameOfFile = JOptionPane.showInputDialog("Where is the File Path to Import Located at?");
File textFile = new File((NameOfFile));
Scanner in = new Scanner (textFile);
//Imports the appropriate text file named "vehicles.txt"//
ArrayList <String> carsArrayList = new ArrayList <String>();
while(in.hasNextLine()){
String line = in.nextLine();
carsArrayList.add(line);
}
in.close();
ArrayList<VehicleClass> vehicleObs = new ArrayList<VehicleClass>();
for (int i= 0; i <carsArrayList.size(); i++){
String temp = carsArrayList.get(i);
VehicleClass one = new VehicleClass ();
String[] sliced = temp.split("\\s+");
one.setPlate(sliced[0]);
int a = Integer.parseInt(sliced[1]);
one.setYear(a);
one.setMfg(sliced[2]);
one.setStyle(sliced[3]);
one.setColor(sliced[4]);
vehicleObs.add(one);
boolean stepTwo = true;
while(stepTwo) {
String search;
search = JOptionPane.showInputDialog("Please choose one of the following search options" + "1 Plate" + "\n" +"2 Year" + "3 Manufacturer" + "\n" + "4 Body Style"+ "\n"+ "5 Color");
int searchOption = Integer.parseInt(search);
String searchVal;
searchVal = JOptionPane.showInputDialog("Enter a value to search for" + "\n" + "All values must be exact in wording, please be careful when using Caps or check for Caps Lock");
searchDialogs(vehicleObs, searchOption, searchVal);
String c;
c = JOptionPane.showInputDialog("Type S to search | E to exit");
String b = "S";
if(c.equalsIgnoreCase(b)){
stepTwo = true;
}
else{
stepTwo= false;
}
}
}
}
public static String plateCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
if(temp.contains(search)){
as.add(list.get(i).toString());
}
}
return alFormat(as);
}
public static String yearCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String mfgCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String styleCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static String colorCheck(ArrayList list, String search){
ArrayList<String> as = new ArrayList<String>();
for (int i = 0; i< list.size(); i++){
String temp = list.get(i).toString();
as.add(list.get(i).toString());
}
return alFormat(as);
}
public static void searchDialogs(ArrayList vehicleObs, int searchOption, String
searchVal){
if(searchOption == 1){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + plateCheck(vehicleObs, searchVal));
}//Outputs data (Plate Numbers) from the text file imported
else if(searchOption == 2){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + yearCheck(vehicleObs, searchVal));
}//Outputs data (Year) from the text file imported
else if(searchOption == 3){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + mfgCheck(vehicleObs, searchVal));
}//Outputs data (Manufacturer) from the text file imported
else if(searchOption == 4){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + styleCheck(vehicleObs, searchVal));
}//Outputs data (Style) from the text file imported
else if(searchOption == 5){
JOptionPane.showMessageDialog(null, "Your following search yielded the following results" + "\n" + colorCheck(vehicleObs, searchVal));
}//Outputs data (Color) from the text file imported
else{
JOptionPane.showMessageDialog(null, "Sorry no results have been found");
}//will only output this message only if nothing is found,//
}
public static String alFormat(ArrayList too){
String tmpString;
String full = "";
for( Object aValue : too){
tmpString = aValue + "\n";
full = full + tmpString;
}
return full;
}
}
VehicleClass.java
public class VehicleClass {
protected String plate;//car plate
protected int year;//car model year
protected String mfg;//manufacturer
protected String style;// car style
protected String color;//color of car
public VehicleClass(){
plate = null;
year = 0000;
style = null;
color = null;
}
public VehicleClass (String e , int r, String g, String y, String c){
plate = e;
year = r;
mfg = g;
style = y;
color = c;
}
public VehicleClass copyVehicle(VehicleClass k){
VehicleClass k1 = new VehicleClass();
k1.setPlate(k.getPlate ());
k1.setYear(k.getYear());
k1.setMfg(k.getMfg());
k1.setStyle(k.getStyle());
k1.setColor(k.getColor());
return k1;
}
public void setPlate(String e){
plate= e;
}
public void setYear(int r){
year = r;
}
public void setMfg(String g){
mfg = g;
}
public void setStyle(String y){
style = y;
}
public void setColor(String c){
color = c;
}
public String getPlate(){
return plate;
}
public int getYear(){
return year;
}
public String getMfg(){
return mfg;
}
public String getStyle(){
return style;
}
public String getColor(){
return color;
}
#Override //need this?
public String toString(){
return (plate + "\t" + year + "\t" + mfg +"\t"+ style + "\t" + color);
}
}
vehicle info file
AB-2323 1900 Japan Sport Black
AB-2323 1990 German Business White
AB-2323 2000 USA Army Blue

How do I store objects created into an ArrayList and return it?

I'm asked to create a method called listOfWorkers in which i will create objects of each type of the 3 workers I have by reading the data from the file "workers.txt" and then store the objects into an ArrayList of type Worker and return it. I have managed to make the objects of each type of the 3 workers with by reading the data from the file, but now I don't know how to store them into an ArrayList. Any help guys?
Class i'm coding in right now
import java.util.*;
import java.io.*;
public class WorkerBenefits
{
public ArrayList<Worker> listOfWorkers()
{
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line,",");
String jobs = st.nextToken();
Jobs jobType = Jobs.valueOf(jobs);
//Engineer Object type
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
}
//Admin. Person. Object type
else if (jobType == Jobs.ADMINISTRATIVE_SECRETARY || jobType == Jobs.ADMINISTRATIVE_ASSISTANT)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double rate = Double.parseDouble(str3);
String str4 = st.nextToken();
double hours = Double.parseDouble(str4);
AdministrativePersonnel ap = new AdministrativePersonnel(name,social,years,jobType,rate,hours);
}
//Management Object type
else if (jobType == Jobs.ENGINEERING_MANAGER || jobType == Jobs.ADMINISTRATIVE_MANAGER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
String str4 = st.nextToken();
double bonus = Double.parseDouble(str4);
Management mang = new Management(name,social,years,jobType,weeklyBen,bonus);
}
}
}
catch (IOException ioe)
{
System.out.println("Something went wrong");
}
return ArrayList;
}
}
Here is the code for the other classes just in case you guys need them:
Jobs
public enum Jobs {ELECTRICAL_ENGINEER, MECHANICAL_ENGINEER, ADMINISTRATIVE_SECRETARY, ADMINISTRATIVE_ASSISTANT, ENGINEERING_MANAGER, ADMINISTRATIVE_MANAGER, NONE};
Worker
public abstract class Worker
{
public String name;
public int socialSecurity;
private int yearsExperience;
public Jobs et = null;
public static int id = 0;
public int currentID = 0;
public Worker ()
{
name = "AnyName";
socialSecurity = 12345;
yearsExperience = 0;
et = Jobs.NONE;
id++;
currentID = id;
}
public Worker (String n, int ss, int ye, Jobs j)
{
id++;
currentID = id;
name = n;
socialSecurity = ss;
yearsExperience = ye;
et = j;
}
public String getName()
{
return name;
}
public int getSocialSecurity()
{
return socialSecurity;
}
public int getYearsExperience()
{
return yearsExperience;
}
public Jobs getJobs()
{
return et;
}
public void setName(String n1)
{
name = n1;
}
public void setSocialSecurity(int ss1)
{
socialSecurity = ss1;
}
public void setYearsExperience(int ye1)
{
yearsExperience = ye1;
}
public void setJobs(Jobs et1)
{
et = et1;
}
public abstract double benefitsCalculation(Jobs et2);
public String toString()
{
String output = "The name is: " + name + "The Job type is: " + et + "The id is: " + currentID;
return output;
}
}
Engineer
public class Engineer extends Worker
{
private double weeklyBenefits;
public Engineer ()
{
super();
weeklyBenefits = 400.00;
}
public Engineer (String n, int ss, int ye, Jobs j, double wb)
{
super(n,ss,ye,j);
weeklyBenefits = wb;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation(Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ELECTRICAL_ENGINEER)
{
benefits = weeklyBenefits+super.getYearsExperience()*120.00;
}
else if (et2 == Jobs.MECHANICAL_ENGINEER)
{
benefits = weeklyBenefits/2+super.getYearsExperience()*120.00;
}
else if (et2 != Jobs.ELECTRICAL_ENGINEER || et2 != Jobs.MECHANICAL_ENGINEER)
{
benefits = 0;
}
return benefits;
}
public double getWeeklyBenefits()
{
return weeklyBenefits;
}
public void setWeeklyBenefits(double wb)
{
weeklyBenefits = wb;
}
public String toString()
{
String output = "The benefit is " + weeklyBenefits + super.toString();
return output;
}
}
Administrative Personnel
public class AdministrativePersonnel extends Worker
{
private double rate;
private double hours;
public AdministrativePersonnel()
{
super();
rate = 10.0;
hours = 10.0;
}
public AdministrativePersonnel(String n, int ss, int ye, Jobs j, double r, double h)
{
super(n,ss,ye,j);
rate = r;
hours = h;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation (Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ADMINISTRATIVE_SECRETARY)
{
benefits = rate*hours+super.getYearsExperience()*15.00;
}
else if(et2 == Jobs.ADMINISTRATIVE_ASSISTANT)
{
benefits = rate*hours+super.getYearsExperience()*25.00;
}
else if (et2 != Jobs.ADMINISTRATIVE_SECRETARY || et2 != Jobs.ADMINISTRATIVE_ASSISTANT)
{
benefits = 0;
}
return benefits;
}
public double getRate()
{
return rate;
}
public double getHours()
{
return hours;
}
public void setRate(double r1)
{
rate = r1;
}
public void setHours(double h1)
{
hours = h1;
}
public String toString()
{
String output = "The rate is: " + rate + "The hours are: " + hours + super.toString();
return output;
}
}
Management
public class Management extends Worker
{
private double weeklyBenefits;
private double bonus;
public Management()
{
super();
weeklyBenefits = 0.0;
bonus = 0.0;
}
public Management(String n, int ss, int ye, Jobs j, double wb, double b)
{
super(n,ss,ye,j);
weeklyBenefits = wb;
bonus = b;
super.setName(n);
super.setSocialSecurity(ss);
super.setYearsExperience(ye);
super.setJobs(j);
}
public double benefitsCalculation (Jobs et2)
{
double benefits = 0.0;
if (et2 == Jobs.ENGINEERING_MANAGER)
{
benefits = weeklyBenefits+bonus;
}
else if(et2 == Jobs.ADMINISTRATIVE_MANAGER)
{
benefits = weeklyBenefits+0.5*bonus;
}
else if (et2 != Jobs.ENGINEERING_MANAGER || et2 != Jobs.ADMINISTRATIVE_MANAGER)
{
benefits = 0;
}
return benefits;
}
public double getWeeklyBenefits()
{
return weeklyBenefits;
}
public double getBonus()
{
return bonus;
}
public void setWeeklyBenefits(double wb)
{
weeklyBenefits = wb;
}
public void setBonus(double b)
{
bonus = b;
}
public String toString()
{
String output = "The weekly benefits are: " + weeklyBenefits + "The bonus is: " + bonus + super.toString();
return output;
}
}
public ArrayList<Worker> listOfWorkers()
{
List<Worker> list=new ArrayList<Worker>();
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
// no change
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
// no change
Worker eng = new Engineer(name,social,years,jobType,weeklyBen);
list.add(eng);
}
else if()
{
//do same as above for other workers
}
}
return list;
}
The listOfWorkers() methods would need to create a list of workers, add each of the new worker object then return the list.
public List<Worker> listOfWorkers()
{
List<Worker> workers = new ArrayList<Worker>();
try
{
File ifile = new File("worker.txt");
Scanner scan = new Scanner(ifile);
while (scan.hasNextLine())
{
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line,",");
String jobs = st.nextToken();
Jobs jobType = Jobs.valueOf(jobs);
//Engineer Object type
if (jobType == Jobs.ELECTRICAL_ENGINEER || jobType == Jobs.MECHANICAL_ENGINEER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
workers.add(eng);
}
//Admin. Person. Object type
else if (jobType == Jobs.ADMINISTRATIVE_SECRETARY || jobType == Jobs.ADMINISTRATIVE_ASSISTANT)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double rate = Double.parseDouble(str3);
String str4 = st.nextToken();
double hours = Double.parseDouble(str4);
AdministrativePersonnel ap = new AdministrativePersonnel(name,social,years,jobType,rate,hours);
workers.add(ap);
}
//Management Object type
else if (jobType == Jobs.ENGINEERING_MANAGER || jobType == Jobs.ADMINISTRATIVE_MANAGER)
{
String name = st.nextToken();
String str1 = st.nextToken();
int social = Integer.parseInt(str1);
String str2 = st.nextToken();
int years = Integer.parseInt(str2);
String str3 = st.nextToken();
double weeklyBen = Double.parseDouble(str3);
String str4 = st.nextToken();
double bonus = Double.parseDouble(str4);
Management mang = new Management(name,social,years,jobType,weeklyBen,bonus);
workers.add(mang);
}
}
}
catch (IOException ioe)
{
System.out.println("Something went wrong");
}
return workers;
}
Before the try block, create a new ArrayList of worker objects:
ArrayList<Worker> workerList = new ArrayList<Worker>();
At the beginning of the while loop, declare a new worker variable but don't create it yet:
Worker worker = null;
Within each if block, assign the result to worker rather than assigning it to a new variable of type Engineer, Management, or AdministrativePersonnel. For example, replace this:
Engineer eng = new Engineer(name,social,years,jobType,weeklyBen);
with this:
worker = new Engineer(name,social,years,jobType,weeklyBen);
This is legal because Engineer, Management, and AdministrativePersonnel are all subclasses of Worker.
Just before the end of the while loop, add your new worker to the list:
workerList.add(worker);
Finally, return workerList from the function.

Categories