How to reset the getters and setters of a constructor - java

in my recent uni work ive been given a task which i believe is to reassign values that have been set by getters and setters. The exact question is
" Edit the product’s main information that shares among all class such as ID,
Description, etc"
My attempt at this question is as followed.
public void editProductInformation() { //Standard level task 2 method 3
this.ID = 456890;
this.description = "Eggs";
this.recommendedUnitPrice = 10;
this.Unit = 6;
this.weight = 750;
}
}
this is also the code for the rest of the class
public class Product {
Scanner input = new Scanner(System.in);
protected int ID;
protected String description;
protected double recommendedUnitPrice;
protected double actualPrice;
protected int Unit = 1;
protected double weight;
protected LocalDate expiaryDate;
protected LocalDate expireDate;
public Product(int ID, String description, double recommendedUnitPrice, int unit, double weight, LocalDate expiarayDate) {
this.ID = ID;
this.description = description;
this.recommendedUnitPrice = recommendedUnitPrice;
this.Unit = unit;
this.weight = weight;
this.expiaryDate = expiarayDate;
}
public int getID() {
return this.ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDescription() {
return this.description;
}
public void setDescripption(String description) {
this.description = description;
}
public double getRecommendedUnitPrice() {
return this.recommendedUnitPrice;
}
public void setRecommendedUnitPrice(double recommendedUnitPrice) {
this.recommendedUnitPrice = recommendedUnitPrice;
}
public int getUnit() {
return this.Unit;
}
public void setUnit(int unit) {
this.Unit = unit;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double Weight) {
this.weight = Weight;
}
public LocalDate getExpiaryDate() {
return expiaryDate;
}
public void setExpiaryDate(LocalDate expiaryDate) {
this.expiaryDate = expiaryDate;
}
public void setPrice() {
System.out.println("Enter the price: ");
this.actualPrice = input.nextDouble();
}
public void setExpireDate() {
System.out.println("Enter the given date: ");
int day = input.nextInt();
int month = input.nextInt();
int year = input.nextInt();
LocalDate date = LocalDate.of(day, month, year);
this.expireDate = date;
}
public void comparePrice() { // Standard level task 2 method 1
if (recommendedUnitPrice == actualPrice) {
System.out.println("Price is equal");
} else if (recommendedUnitPrice < actualPrice) {
System.out.println("Price is less");
} else if (recommendedUnitPrice > actualPrice) {
System.out.println("Price is more");
}
}
public void verifyExpireProduct() { //Standard level task 2 method 2
if(expireDate == expiaryDate) {
System.out.println("Product is expired");
}
else System.out.println("Product is not expired");
}
I understand this question might not be explained well enough so i understand if people wish to downvote it. Any insight or help is much appreciated!

You can make an object of this class and then by using setter function defined in class you can set the value .
Product p1 = new Product();
p1.setId(5);
//This will set the Id to 5

Related

Compare Duplicate Data From a List with Inputed Data

I want to check duplicate IDs from a list with the data I inputted, then increment the qty variable in the list. If it's new data, it will add a new list.
This is my code
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
}
Even if I input new data it always increments the qty of old data and the new data is not added (basically always end in the "else" section).
Code for inputing data
Gudang gudang1 = new Gudang(1,1);
System.out.println("ID: ");
int id = input.nextInt();
System.out.println("Jumlah: ");
int qty = input.nextInt();
System.out.println("Nama: ");
String name = input.next();
Barang barang = new Barang(id,name,qty);
gudang1.addBarang(barang);
Barang Class
public class Barang {
public static int id;
private String name;
private int qty;
public Barang(int id, String name, int qty) {
this.id = id;
this.name = name;
this.qty = qty;
}
public Barang(){
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getQty() {
return qty;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Barang{" + "id=" + id + ", name=" + name + ", qty=" + qty + '}';
}
Gudang Class
public class Gudang {
public static int id;
private int location;
public List<Barang> list = new ArrayList<Barang>();
public Gudang(int id, int location) {
Gudang.id = id;
this.location = location;
}
public int getId() {
return id;
}
public int getLocation() {
return location;
}
public List<Barang> getList() {
return list;
}
public void setId(int id) {
this.id = id;
}
public void setLocation(int location) {
this.location = location;
}
public void setList(List<Barang> list) {
this.list = list;
}
public void addBarang(Barang barang){
int id_barang = barang.getId();
if(this.list.isEmpty())
{
list.add(barang);
}
else
{
for(int i=0;i<list.size();i++)
{
if(list.get(i).getId() != id_barang)
{
list.add(barang);
System.out.println("Added");
break;
}
if(list.get(i).getId() == id_barang)
{
int new_qty = list.get(i).getQty()+barang.getQty();
list.get(i).setQty(new_qty);
}
}
}
System.out.println("Size List = "+list.size());
}
public void duplicate(List<Barang> list2)
{
this.list.addAll(list2);
}
public void clearBarang(){
this.list.clear();
}
public void display(){
for(Barang barang: this.list){
System.out.println(barang);
}
}
IE : If I have id=1 and qty=1, then input a new data with id=2 and qty=2, the final result will end up with id=2 and qty=3. No new data int he list were added.
try using .equals to compare if the data exist in your list
Please check if ids are duplicate between your old and new data.
If you ids are unique then you can take advantage of Map and put id as key and barang object as value. Whenever you successfully lookup map increment quantity field of object.
At first guess i would change:
if(list.get(i).getId() != id_barang)
to:
if(list.get(i).getId() != barang.getId())
maybe id_barang is not the same as the id stored in the barang object.

Adding Items to my inventory in Java

I am making a text-based game on JavaFX, and after I hit a tree, I want to get Oak logs.
I have already built my inventory, and I have put default items in it such as Water, Bread, etc.
I am trying to add my Oak Logs to my inventory, but nothing is working.
Here is a part of my code:
Item ItemList[] = {new Bread(), new OakLog()};
Optional<ButtonType> result = alert.showAndWait();
if(result.get() == buttonTypeOak) {
woodcuttingXP = woodcuttingXP + oakXP;
dialogue.appendText("You swing at an Oak tree. + " + oakXP + "XP.\n");
dialogue.appendText("You gathered 1 log.\n");
mainCharacter.getInventory().add(new OakLog());
}
Here is my Item Class:
package game;
public class Item {
private String name;
private int weight;
private int quantity;
private int value;
private String description;
public Item(String name, int value, String description) {
this.name = name;
this.value = value;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return getName();
}
}
And finally, here is my Character class:
package game;
import java.util.ArrayList;
import beverages.Water;
import items.OakLog;
import rawFood.Bread;
public class Character {
private String name;
private int hydrationLevel;
private int healthLevel;
private int hungerLevel;
private int woodcuttingLevel;
public int getWoodcuttingLevel() {
return woodcuttingLevel;
}
public void setWoodcuttingLevel(int woodcuttingLevel) {
this.woodcuttingLevel = woodcuttingLevel;
}
public int getHungerLevel() {
return hungerLevel;
}
public void setHungerLevel(int hungerLevel) {
this.hungerLevel = hungerLevel;
}
private ArrayList<Item> inventory = new ArrayList<Item>();
public ArrayList<Item> getInventory() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
//creates a person with two basic items
public Character(String name){
this.name = name;
this.hydrationLevel = 100;
this.healthLevel = 100;
this.hungerLevel = 100;
this.woodcuttingLevel = 1;
addToInventory (new Bread());
addToInventory (new OakLog());
addToInventory (new Water());
}
//GETTERS AND SETTERS
public String getName() {
return name;
}
public int getHydrationLevel() {
return hydrationLevel;
}
public void setHydrationLevel(int hydrationLevel) {
this.hydrationLevel = hydrationLevel;
}
public int getHealthLevel() {
return healthLevel;
}
public void setHealthLevel(int healthLevel) {
this.healthLevel = healthLevel;
}
//END GETTERS AND SETTERS
/*Method Name: eat()
*Method Inputs: a piece of food
*Method Purpose: Will allow the user to eat food
*/
public Item getItemFromInventory(int index){
Item item = inventory.get(index);
return item;
}
public void addToInventory(Item item){
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
else{
item.setQuantity(1);
inventory.add(item);
}
}
public String toString(){
return "Character Stats:\nName:" + getName() + "\nHydration: " + getHydrationLevel() + "\nHealth: " + getHealthLevel() + "\nWoodcutting: " + getWoodcuttingLevel();
}
}
In your code, you have:
if(inventory.contains(item)){
item.setQuantity(item.getQuantity()+1);
}
This just updates the quantity of the local variable item in the method, not the item in the inventory.

Array sorting printing and summing

What would be the simplest method to print this array broken down into each mobile phone as a product number, name department etc, and then re print the same information sorted by product name. I have tried a couple different methods and am already passed the turn in date for the assignment but still need to figure it out for upcoming assignment this weekend. When I try to implement the comparator on MobilePhone class it forces me to make it abstract or use #override but I can't figure out where or what to override to make it work because the abstract class causes a multitude of other problems.
package InventoryPro2;
import java.util.*;
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { //assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
}
public class InventoryPro2 {
MobilePhone mobilephone = new MobilePhone();
public static void main(String args[]) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();//skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println();
}
}
(Also, what is the best way to take just one piece of information out of each part of the array such as the totalInv and total all of those numbers to print?) Do I have unnecessary code here or have I done everything right thus far? I have to say that learning this coding language in an online format has not been a very enjoyable experience thus far..
Here is how to sort by name
import java.util.Arrays;
import java.util.Comparator;
public class AppInventoryPro2 {
public static void main(String... args) {
System.out.println("Mobile Phone Inventory Program");
System.out.println();// skips a line
MobilePhone[] phones = new MobilePhone[5];
phones[0] = new MobilePhone();
phones[0].setproductNumber(1);
phones[0].setname("Motorola");
phones[0].setdepartment("Electronics");
phones[0].setunitPrice(150.10);
phones[0].setunitsInStock(98);
phones[1] = new MobilePhone();
phones[1].setproductNumber(2);
phones[1].setname("Samsung");
phones[1].setdepartment("Electronics");
phones[1].setunitPrice(199.99);
phones[1].setunitsInStock(650);
phones[2] = new MobilePhone();
phones[2].setproductNumber(3);
phones[2].setname("Nokia");
phones[2].setdepartment("Electronics");
phones[2].setunitPrice(200.25);
phones[2].setunitsInStock(125);
phones[3] = new MobilePhone();
phones[3].setproductNumber(4);
phones[3].setname("LG");
phones[3].setdepartment("Electronics");
phones[3].setunitPrice(100.05);
phones[3].setunitsInStock(200);
phones[4] = new MobilePhone();
phones[4].setproductNumber(5);
phones[4].setname("IPhone");
phones[4].setdepartment("Electronics");
phones[4].setunitPrice(299.99);
phones[4].setunitsInStock(150);
System.out.println("Order of inventory before sorting:");
System.out.println(Arrays.toString(phones));
Arrays.sort(phones, new Comparator<MobilePhone>() {
#Override
public int compare(MobilePhone mp1, MobilePhone mp2) {
return mp1.getname().compareTo(mp2.getname());
}
});
System.out.println("Order of inventory after sorting by name:");
System.out.println(Arrays.toString(phones));
}
}
class MobilePhone {
private double productNumber; // Variables
private String name;
private String department;
private double unitsInStock;
private double unitPrice;
public MobilePhone() {
this(0.0, "", "", 0.0, 0.0);
}
public MobilePhone(double productNumber, String name, String department,
double unitsInStock, double unitPrice) { // assign variables
this.productNumber = productNumber;
this.name = name;
this.department = department;
this.unitsInStock = unitsInStock;
this.unitPrice = unitPrice;
}
public double getproductNumber() { // retrieve values
return productNumber;
}
public String getname() {
return name;
}
public String getdepartment() {
return department;
}
public double getunitPrice() {
return unitPrice;
}
public double getunitsInStock() {
return unitsInStock;
}
public void setproductNumber(double productNumber) {
this.productNumber = productNumber;
}
public void setname(String name) {
this.name = name;
}
public void setdepartment(String department) {
this.department = department;
}
public void setunitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public void setunitsInStock(double unitsInStock) {
this.unitsInStock = unitsInStock;
}
public double gettotalInv() {
return getunitPrice() * getunitsInStock();
}
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber + ", name=" + name
+ ", department=" + department + ", unitsInStock="
+ unitsInStock + ", unitPrice=" + unitPrice + "]";
}
}
1 - To print content of MobilePhone class: Override default toString method like this:
#Override
public String toString() {
return "MobilePhone [productNumber=" + productNumber +
", name=" + name + ']'; // add more info if needed
}
2 - To allow sorting by name: Have MobilePhone class implement Comparable interface like
this:
class MobilePhone implements Comparable {
...
#Override
public int compareTo(Object o) {
MobilePhone m = (MobilePhone) o;
return (this.name.compareTo(o.name));
}
}
EDIT: To print your array of MobilePhone object you can do:
System.out.printf("Phones: %s%n", Arrays.toString(phones));

Cant find Symbol error

The compiler gives me an error message saying it can't find movies[x].getTitle() and movies[x].getYear. I've been wondering if it's a problem with going through the interface to get to the classes
Here is the error:
MathewBorumP5.java:68: error: cannot find symbol
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", movies[x]
.getTitle(),
^
symbol: method getTitle()
location: interface Profitable
MathewBorumP5.java:69: error: cannot find symbol
movies[x].getYear(), movies[x].calcRevenue(),
^
symbol: method getYear()
location: interface Profitable
2 errors
Here is my client class:
import java.util.Scanner;
public class MathewBorumP5 {
public static void main(String[] args) {
int choice;
boolean restart = true;
Scanner input = new Scanner(System.in);
Profitable[] movies = new Profitable[6];
movies[0] = new Animated("Beauty and the Beast", "Gary Trousdale", 1991,
10.0, 5.0, 2.0);
movies[1] = new Animated("Peter Pan", "Clyde Geronimi", 1953, 2.0, 1.2,
.5);
movies[2] = new Documentary("Planet Earth", "Alastair Fothergill", 2006,
10, 20, 5);
movies[3] = new Documentary("Drain the Ocean", "Steve Nichols", 2009, 9,
2,3);
movies[4] = new Drama("The Shawshank Redemption", "Frank Darabont",
1994, 89, 7, 2);
movies[5] = new Drama("The Godfather", "Francis Coppola", 1972, 10, 3,
5);
do {
menu();
System.out.print("Enter a number from 1 - 5: ");
choice = input.nextInt();
System.out.print("\n");
switch(choice) {
case 1:
item1(movies);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
restart = false;
break;
default:
System.out.print("You didn't enter a number between 1"
+ " and 5.\n");
break;
}
} while(restart == true);
}
public static void menu() {
System.out.print("Warren Moore Movie Menu\n");
System.out.print("1. Show the list of movies in the array\n");
System.out.print("2. Display the total number of movies and the total" +
" revenues\n");
System.out.print("3. Search movie by title\n");
System.out.print("4. Display movies sorted by profit in decreasing" +
" order\n");
System.out.print("5. Exit\n");
}
public static void item1(Profitable[] movies) {
double revenue;
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", "Title", "Year",
"Revenue", "Profit", "Category");
for(int x = 0; x <= 6; x++) {
revenue = movies[x].calcRevenue();
System.out.printf("%-26s%-6s%-10s%-9s%-11s\n", movies[x].getTitle(),
movies[x].getYear(), movies[x].calcRevenue(),
movies[x].calcProfit(revenue), movies[x].category());
}
}
}
Here is my superclass:
public class Movie implements Profitable {
protected String title;
protected String director;
protected int year;
protected double productionCost;
private int totalMovies = 0;
public Movie() {
totalMovies++;
}
public Movie(String newTitle, String newDirector, int newYear,
double newCost) {
totalMovies++;
title = newTitle;
director = newDirector;
year = newYear;
productionCost = newCost;
}
public int getTotalMovies() {
return totalMovies;
}
public String getTitle() {
return title;
}
public void setTitle(String newTitle) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getProductionCost() {
return productionCost;
}
public void setProductionCost(double productionCost) {
this.productionCost = productionCost;
}
public String toString() {
return "";
}
}
Here are my separate classes.
public class Animated extends Movie implements Profitable {
private double rate;
private double income;
public Animated() {
super();
}
public Animated(String title, String director, int year, double cost,
double rate, double income) {
super(title, director, year, cost);
this.rate = rate;
this.income = income;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
public String category() {
return "Animated";
}
public double calcRevenue() {
return (income * rate);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
Number 2
public class Documentary extends Movie implements Profitable {
private int distributors;
private double premium;
public Documentary() {
super();
}
public Documentary(String title, String director, int year, double cost,
int distributors, double premium) {
super(title, director, year, cost);
this.distributors = distributors;
this.premium = premium;
}
public int getDistributors() {
return distributors;
}
public void setDistributors(int distributors) {
this.distributors = distributors;
}
public double getPremium() {
return premium;
}
public void setPremium(double premium) {
this.premium = premium;
}
public String category() {
return "Documentary";
}
public double calcRevenue() {
return (distributors * premium);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
Number 3
public class Drama extends Movie implements Profitable {
private int tickets;
private double avgPrice;
public Drama() {
super();
}
public Drama(String title, String director, int year, double cost,
int tickets, double avgPrice) {
super(title, director, year, cost);
this.tickets = tickets;
this.avgPrice = avgPrice;
}
public int getTickets() {
return tickets;
}
public void setTickets(int tickets) {
this.tickets = tickets;
}
public String category() {
return "Drama";
}
public double calcRevenue() {
return (tickets * avgPrice);
}
public double calcProfit(double revenue) {
return (revenue - super.productionCost);
}
public String toString() {
return (super.toString() + "");
}
}
And finally my interface.
public interface Profitable {
public abstract String category();
public abstract double calcRevenue();
public abstract double calcProfit(double revenue);
}
The Profitable interface doesn't have the methods that you're trying to call, and so the compiler is correct to complain about this to you. The array variable doesn't know what type of object each array item might hold, and in fact one could hold one type of item only to have it changed later, so it makes sense for the compiler to behave this way. A kludge would be to test each item held by the array to see what type it actually is, say by using instanceof, but this is a very fragile solution and is not recommended. Safest is to only call Profitable methods on Profitable array items and to try to use the magic of polymorphism to allow each object to do different behaviors for the same method call.
Note that if all of the items held by the array will always be Movie or Movie child items, then by all means use an array of Movie rather than an array of Profitable.
You are correct, the issue is with your Profitable interface.
When you create the array item(Profitable[] movies), this means that only the methods defined in this interface will be available to you.
An array of Movie objects is probably what you are after here. All of those objects appear extend Movie and implement Profitable, so you will able to access everything this way.

Homework Help; Reading from multiple files into Vectors/Arrays

Okay my assignment is to read in from 2 separate files. The first file reads in "HallOfFameMember" and should then be stored in a vector.
The second should read in and then be stored to an array of HallOfFame
The HallOfFameMember object has 10 fields. In order firstName, lastName, deceased, month born, day born, year born, totalEarned, yearsPlayed, yearInducted, hall of fame id
The day/month/year born are all going to a separate class to create a date born. The date born is then set within HallOfFameMember. The Fields for a record will be separated by varying numbers of spaces and/or tabs (whitespaces).
After reading a record from this file, call the 10-arg constructor of HallOfFameMember, using the fields from the record as arguments in the constructor call. Add this new HallOfFameMember object to tempHallOfFameMemberVec.
The HallOfFame object has 5 fields. In order hallOfFameId, city, costToVisit, numberOfVisitorsPerYear, and name.
After reading a record from this file, call the 5-arg constructor of class HallOfFame, using the arguments obtained from the line in the file. Add this new HallOfFame object to tempHallOfFameArr.
This is all to be done from the command line.
I know that my current code will not work, I was just trying to figure out some way to do this. Vectors are completely new to me, along with BufferedReader, and I've been trying to use the examples on javapractice.com as well as a few other sites for reference. I know it will be something small that I am overlooking/missing and Ill have a duh moment when I figure it out.
At any rate my current question is this.
How do I read in from a file that has "any number of white spaces/tabs" as the delimiter. And then parse that into the appropriate fields within the appropriate class?
Giving me the code isn't gonna help, if you could just point me to a website or link that I can read to have my duh moment that would be great.
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Vector;
public class HW4 {
/**
* #param args
*/
public static void main(String[] args) {
FileReader inputFileA = new FileReader("");
FileReader inputFileB = new FileReader("");
BufferedReader inputB = new BufferedReader(inputFileB);
Vector<HallOfFameMember> tempHallOfFameMemberVec = new Vector<HallOfFameMember>();
try{
BufferedReader inputA = new BufferedReader(inputFileA);
try {
String line = null;
while ((line = inputA.readLine()) != null){
}
}
}
String newHallOfFameLine = inputB.toString();
String delims = "[ \t]";
HallOfFame[] tempHallOfFameArr = newHallOfFameLine.split(delims);
for (int i = 0; i < args.length; i += 5) {
tempHallOfFameArr[i/5].setHallOfFameId(Integer.parseInt(args[i]));
tempHallOfFameArr[i/5].setCity(args[i+1]);
tempHallOfFameArr[i/5].setCostToVisit(Integer.parseInt(args[i+2]));
tempHallOfFameArr[i/5].setNumberOfVisitorsPerYear(Integer.parseInt(args[i+3]));
tempHallOfFameArr[i/5].setName(args[i+4]);
}
}
class HallOfFameMember {
private String firstName;
private String lastName;
private boolean deceased;
private int dateOfBirth;
private double totalEarned;
private int yearsPlayed;
private int yearInducted;
private int HallOfFameId;
public HallOfFameMember() {
}
public HallOfFameMember(String firstName, String lastName,
boolean deceased, int day, int month, int year, double totalEarned,
int yearsPlayed, int yearInducted, int hallOfFameId) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.deceased = deceased;
this.dateOfBirth = month + day + year;
this.totalEarned = totalEarned;
this.yearsPlayed = yearsPlayed;
this.yearInducted = yearInducted;
HallOfFameId = hallOfFameId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isDeceased() {
return deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
public int getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(int dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public double getTotalEarned() {
return totalEarned;
}
public void setTotalEarned(double totalEarned) {
this.totalEarned = totalEarned;
}
public int getYearsPlayed() {
return yearsPlayed;
}
public void setYearsPlayed(int yearsPlayed) {
this.yearsPlayed = yearsPlayed;
}
public int getYearInducted() {
return yearInducted;
}
public void setYearInducted(int yearInducted) {
this.yearInducted = yearInducted;
}
public int getHallOfFameId() {
return HallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
HallOfFameId = hallOfFameId;
}
public double averageYearlySalary(double averageYearlySalary) {
return averageYearlySalary = (totalEarned / yearsPlayed);
}
}
class Date {
private int month;
private int day;
private int year;
public Date(int month, int day, int year) {
super();
this.month = month;
this.day = day;
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
class HallOfFame {
private int hallOfFameId;// ID of the hall of fame
private String name;// Name of the hall of fame
private String city;// the city in which the hall of fame is located
private double costToVisit;// cost in dollars for a visitor to a hall of
// fame for 1 day
private int numberOfVisitorsPerYear;
private static final double maxCostToVisit = 37.50;
public HallOfFame() {
}
public HallOfFame(int hallOfFameId, String name, String city,
double costToVisit, int numberOfVisitorsPerYear) {
super();
this.hallOfFameId = hallOfFameId;
this.name = name;
this.city = city;
this.costToVisit = costToVisit;
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public int getHallOfFameId() {
return hallOfFameId;
}
public void setHallOfFameId(int hallOfFameId) {
this.hallOfFameId = hallOfFameId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getCostToVisit() {
if (costToVisit <= maxCostToVisit) {
return costToVisit;
} else
return maxCostToVisit;
}
public void setCostToVisit(double costToVisit) {
this.costToVisit = costToVisit;
}
public int getNumberOfVisitorsPerYear() {
return numberOfVisitorsPerYear;
}
public void setNumberOfVisitorsPerYear(int numberOfVisitorsPerYear) {
this.numberOfVisitorsPerYear = numberOfVisitorsPerYear;
}
public static double getMaxcosttovisit() {
return maxCostToVisit;
}
public double totalAnnualRevenue(double totalAnnualRevenue) {
totalAnnualRevenue += costToVisit * numberOfVisitorsPerYear;
return totalAnnualRevenue;
}
}
class ReportWriter{
private Vector<HallOfFameMember> hallOfFameMemberVec;
private HallOfFame[] hallOfFameArr;
public ReportWriter() {
}
public Vector<HallOfFameMember> getHallOfFameMemberVec() {
return hallOfFameMemberVec;
}
public void setHallOfFameMemberVec(Vector<HallOfFameMember> hallOfFameMemberVec) {
this.hallOfFameMemberVec = hallOfFameMemberVec;
}
public HallOfFame[] getHallOfFameArr() {
return hallOfFameArr;
}
public void setHallOfFameArr(HallOfFame[] hallOfFameArr) {
this.hallOfFameArr = hallOfFameArr;
}
public void displayReports(){
}
}
A couple tips:
I don't want to do your homework for you, but I can't think of a quick tutorial to point you to that covers exactly what you're doing.
You're on the right track with .split, but your delimiter expression won't work for multiple spaces/tabs. Try this:
String delims = "\\s+";
That will break up your string on any consecutive sequence of one or more whitespace characters.
Also, you need to move the split up into your while loop, as well as the creation of each HallOfFameMember object. In each iteration of the loop you want to:
Split the line that you read from the file to create an array of strings representing the values for one record.
Create a new HallOfFameMember using the values from your string array. (tempHallOfFameArr[0] for first name, tempHallOfFameArr[1] for last name, etc.)
Add the new HallOfFameMember that you created to your vector
If you'd like more detail on any of these steps, I'm happy to elaborate.

Categories