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();
}
}
}
}
Related
I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}
Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}
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;
}
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.
I've had this problem throughout multiple programs, but I can't remember how I fixed it last time. In the second while loop in my body, the second sentinel value is never read in for some reason. I've been trying to fix it for a while now, thought I might see if anyone had any clue.
import java.text.DecimalFormat; // imports the decimal format
public class Car {
// Makes three instance variables.
private String make;
private int year;
private double price;
// Makes the an object that formats doubles.
public static DecimalFormat twoDecPl = new DecimalFormat("$0.00");
// Constructor that assigns the instance variables
// to the values that the user made.
public Car(String carMake,int carYear, double carPrice)
{
make = carMake;
year = carYear;
price = carPrice;
}
// Retrieves variable make.
public String getMake()
{
return make;
}
// Retrieves variable year.
public int getYear()
{
return year;
}
// Retrieves variable price.
public double getPrice()
{
return price;
}
// Checks if two objects are equal.
public boolean equals(Car c1, Car c2)
{
boolean b = false;
if(c1.getMake().equals(c2.getMake()) && c1.getPrice() == c2.getPrice() &&
c1.getYear() == c2.getYear())
{
b = true;
return b;
}
else
{
return b;
}
}
// Turns the object into a readable string.
public String toString()
{
return "Description of car:" +
"\n Make : " + make +
"\n Year : " + year +
"\n Price: " + twoDecPl.format(price);
}
}
import java.util.Scanner; // imports a scanner
public class CarSearch {
public static void main(String[] args)
{
// initializes all variables
Scanner scan = new Scanner(System.in);
final int SIZE_ARR = 30;
Car[] carArr = new Car[SIZE_ARR];
final String SENT = "EndDatabase";
String carMake = "";
int carYear = 0;
double carPrice = 0;
int count = 0;
int pos = 0;
final String SECSENT = "EndSearchKeys";
final boolean DEBUG_SW = true;
// Loop that goes through the first list of values.
// It then stores the values in an array, then uses the
// values to make an object.
while(scan.hasNext())
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car car1 = new Car(carMake, carYear, carPrice);
carArr[count] = car1;
count++;
}
// Calls the method debugSwitch to show the debug information.
debugSwitch(carArr, DEBUG_SW, count);
// Calls the method printData to print the database.
printData(carArr, count);
// Loops through the second group of values and stores them in key.
// Then, it searches for a match in the database.
**while(scan.hasNext())**
{
if(scan.hasNext())
{
carMake = scan.next();
}
else
{
System.out.println("ERROR - not a String");
System.exit(0);
}
if(carMake.equals(SECSENT))
{
break;
}
if(scan.hasNextInt())
{
carYear = scan.nextInt();
}
else
{
System.out.println("ERROR - not an int" + count);
System.exit(0);
}
if(scan.hasNextDouble())
{
carPrice = scan.nextDouble();
}
else
{
System.out.println("ERROR - not a double");
System.exit(0);
}
Car key = new Car(carMake, carYear, carPrice);
// Stores the output of seqSearch in pos.
// If the debug switch is on, then it prints these statements.
if(DEBUG_SW == true)
{
System.out.println("Search, make = " + key.getMake());
System.out.println("Search, year = " + key.getYear());
System.out.println("Search, price = " + key.getPrice());
}
System.out.println("key =");
System.out.println(key);
pos = seqSearch(carArr, count, key);
if(pos != -1)
{
System.out.println("This vehicle was found at index = " + pos);
}
else
{
System.out.println("This vehicle was not found in the database.");
}
}
}
// This method prints the database of cars.
private static void printData(Car[] carArr, int count)
{
for(int i = 0; i < count; i++)
{
System.out.println("Description of car:");
System.out.println(carArr[i]);
}
}
// Searches for a match in the database.
private static int seqSearch(Car[] carArr, int count, Car key)
{
for(int i = 0; i < count; i++)
{
boolean b = key.equals(key, carArr[i]);
if(b == true)
{
return i;
}
}
return -1;
}
// Prints debug statements if DEBUG_SW is set to true.
public static void debugSwitch(Car[] carArr, boolean DEBUG_SW, int count)
{
if(DEBUG_SW == true)
{
for(int i = 0; i < count; i++)
{
System.out.println("DB make = " + carArr[i].getMake());
System.out.println("DB year = " + carArr[i].getYear());
System.out.println("DB price = " + carArr[i].getPrice());
}
}
}
}
I think this is your problem, but I might be wrong:
Inside your while loop, you have these calls:
next()
nextInt()
nextDouble()
The problem is that the last call (nextDouble), will not eat the newline. So to fix this issue, you should add an extra nextLine() call at the end of the two loops.
What happens is that the next time you call next(), it will return the newline, instead of the CarMake-thing.
I'm trying to calclulate the best way to delete a node in a family tree. First, a little description of how the app works.
My app makes the following assumption:
Any node can only have one partner. That means that any child a single node has, it will also be the partner nodes child too. Therefore, step relations, divorces etc aren't compensated for. A node always has two parents - A mother and father cannot be added seperately. If the user doesn't know the details - the nodes attributes are set to a default value.
Also any node can add parents, siblings, children to itself. Therefore in law relationships can be added.
EDIT: After studying Andreas' answer, I have come to realise that my code may need some re-working. I'm trying to add my source but it exceeds the limit of charracters...Any advice?
Here is the FamilyTree Class:
package familytree;
import java.io.PrintStream;
public class FamilyTree {
private static final int DISPLAY_FAMILY_MEMBERS = 1;
private static final int ADD_FAMILY_MEMBER = 2;
private static final int REMOVE_FAMILY_MEMBER = 3;
private static final int EDIT_FAMILY_MEMBER = 4;
private static final int SAVE_FAMILY_TREE = 5;
private static final int LOAD_FAMILY_TREE = 6;
private static final int DISPLAY_ANCESTORS = 7;
private static final int DISPLAY_DESCENDANTS = 8;
private static final int QUIT = 9;
private Input in;
private Family family;
private PrintStream out;
public FamilyTree(Input in, PrintStream out) {
this.in = in;
this.out = out;
family = new Family();
}
public void start() {
out.println("\nWelcome to the Family Tree Builder");
initialise();
while (true) {
displayFamilyTreeMenu();
int command = getCommand();
if (quit(command)) {
break;
}
executeOption(command);
}
}
private int getCommand() {
return getInteger("\nEnter command: ");
}
private int getInteger(String message) {
while (true) {
out.print(message);
if (in.hasNextInt()) {
int n = in.nextInt();
in.nextLine();
return n;
} else {
in.nextLine();
out.println("Your input was not understood. Please try again.");
}
}
}
//good
private void displayFamilyTreeMenu() {
out.println("\nFamily Tree Menu");
out.println(DISPLAY_FAMILY_MEMBERS + ". Display Family Members");
out.println(ADD_FAMILY_MEMBER + ". Add Family Member");
out.println(REMOVE_FAMILY_MEMBER + ". Remove Family Member");
out.println(EDIT_FAMILY_MEMBER + ". Edit Family Member");
out.println(SAVE_FAMILY_TREE + ". Save Family Tree");
out.println(LOAD_FAMILY_TREE + ". Load Family Tree");
out.println(DISPLAY_ANCESTORS + ". Display Ancestors");
out.println(DISPLAY_DESCENDANTS + ". Display Descendants");
out.println(QUIT + ". Quit");
}
//good
private boolean quit(int opt) {
return (opt == QUIT) ? true : false;
}
//good
private void executeOption(int choice) {
switch (choice) {
case DISPLAY_FAMILY_MEMBERS:
displayFamilyMembers();
break;
case ADD_FAMILY_MEMBER:
addFamilyMember();
break;
case REMOVE_FAMILY_MEMBER:
removeMember();
break;
case EDIT_FAMILY_MEMBER:
editMember();
break;
case SAVE_FAMILY_TREE:
saveFamilyTree();
break;
case LOAD_FAMILY_TREE:
loadFamilyTree();
break;
case DISPLAY_ANCESTORS:
displayAncestors();
break;
case DISPLAY_DESCENDANTS:
displayDescendants();
break;
default:
out.println("Not a valid option! Try again.");
break;
}
}
private void removeMember() {
displayFamilyMembers();
int choice = selectMember();
if (choice >= 0) {
FamilyMember f = family.getFamilyMember(choice);
if (f.getIndex() == 0) {
out.println("Cannot delete yourself!");
return;
}
deleteMember(f);
}
}
private void deleteMember(FamilyMember f) {
//remove from tree
family.removeMember(f);
//remove all links to this person
if (f.hasParents()) {
f.getMother().removeChild(f);
f.getFather().removeChild(f);
}
if(f.getPartner()!=null){
f.getPartner().setPartner(null);
f.setPartner(null);
}
if (f.hasChildren()) {
for (FamilyMember member : f.getChildren()) {
if (f == member.getMother()) {
member.setMother(null);
}
if (f == member.getFather()) {
member.setFather(null);
}
if (f == member.getPartner()) {
member.setPartner(null);
}
}
}
}
private void saveFamilyTree() {
out.print("Enter file name: ");
String fileName = in.nextLine();
FileOutput output = new FileOutput(fileName);
family.save(output);
output.close();
saveRelationships();
}
private void saveRelationships() {
FileOutput output = new FileOutput("Relationships.txt");
family.saveRelationships(output);
output.close();
}
private void loadFamilyTree() {
out.print("Enter file name: ");
String fileName = in.nextLine();
FileInput input = new FileInput(fileName);
family.load(input);
input.close();
loadRelationships();
}
private void loadRelationships() {
FileInput input = new FileInput("Relationships.txt");
family.loadRelationships(input);
input.close();
}
//for selecting family member for editing adding nodes etc
private void displayFamilyMembers() {
out.println("\nDisplay Family Members");
int count = 0;
for (FamilyMember member : family.getFamilyMembers()) {
out.println();
if (count + 1 < 10) {
out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName());
out.println(" " + member.getGender());
out.println(" " + member.getDob());
out.println(" Generation: " + (member.getGeneration() + 1));
} else {
out.println((count + 1) + ". " + member.getFirstName() + " " + member.getLastName());
out.println(" " + member.getGender());
out.println(" " + member.getDob());
out.println(" Generation: " + (member.getGeneration() + 1));
}
count++;
}
}
private int selectRelative() {
out.println("\nSelect Relative");
out.println("1. Add Parents");
out.println("2. Add Child");
out.println("3. Add Partner");
out.println("4. Add Sibling");
//out.print("\nEnter Choice: ");
//int choice = in.nextInt();
int choice = getInteger("\nEnter Choice: ");
if (choice > 0 && choice < 5) {
return choice;
}
return (-1);
}
private void addFamilyMember() {
if (family.getFamilyMembers().isEmpty()) {
out.println("No Members To Add To");
return;
}
int memberIndex = selectMember();
if (memberIndex >= 0) {
FamilyMember member = family.getFamilyMember(memberIndex);
int relative = selectRelative();
if (relative > 0) {
out.println("\nAdd Member");
//if choice is valid
switch (relative) {
case 1:
//adding parents
FamilyMember mum, dad;
if (!member.hasParents()) {
out.println("Enter Mothers Details");
mum = addMember(relative, "Female");
out.println("\nEnter Fathers Details");
dad = addMember(relative, "Male");
member.linkParent(mum);
member.linkParent(dad);
mum.linkPartner(dad);
mum.setGeneration(member.getGeneration() - 1);
dad.setGeneration(member.getGeneration() - 1);
sortGenerations();
} else {
out.println(member.getFirstName() + " " + member.getLastName() + " already has parents.");
}
break;
case 2:
//adding child
if (member.getPartner() == null) {
FamilyMember partner;
if (member.getGender().equals("Male")) {
out.println("Enter Mothers Details");
partner = addMember(1, "Female");
} else {
out.println("Enter Fathers Details");
partner = addMember(1, "Male");
}
//create partner
member.linkPartner(partner);
partner.setGeneration(member.getGeneration());
out.println();
}
out.println("Enter Childs Details");
FamilyMember child = addMember(relative, "");
child.linkParent(member);
child.linkParent(member.getPartner());
child.setGeneration(member.getGeneration() + 1);
sortGenerations();
break;
case 3:
//adding partner
if (member.getPartner() == null) {
out.println("Enter Partners Details");
FamilyMember partner = addMember(relative, "");
member.linkPartner(partner);
partner.setGeneration(member.getGeneration());
} else {
out.println(member.getFirstName() + " " + member.getLastName() + " already has a partner.");
}
break;
case 4:
//adding sibling
if (member.getFather() == null) {
out.println("Enter Mothers Details");
mum = addMember(1, "Female");
out.println("\nEnter Fathers Details");
dad = addMember(1, "Male");
member.linkParent(mum);
member.linkParent(dad);
mum.linkPartner(dad);
mum.setGeneration(member.getGeneration() - 1);
dad.setGeneration(member.getGeneration() - 1);
sortGenerations();
out.println("\nEnter Siblings Details");
} else {
out.println("Enter Siblings Details");
}
FamilyMember sibling = addMember(relative, "");
//create mum and dad
mum = member.getMother();
dad = member.getFather();
sibling.linkParent(mum);
sibling.linkParent(dad);
sibling.setGeneration(member.getGeneration());
break;
}
} else {
out.println("Invalid Option!");
}
} else {
out.println("Invalid Option!");
}
}
private int selectMember() {
displayFamilyMembers();
//out.print("\nSelect Member: ");
//int choice = in.nextInt();
int choice = getInteger("\nSelect Member: ");
if (choice > 0 && choice <= family.getFamilyMembers().size()) {
return (choice - 1);
}
return -1;
}
private void editMember() {
int choice = selectMember();
if (choice >= 0) {
out.println("Select Detail To Edit: ");
out.println("1. Name");
out.println("2. Gender");
out.println("3. Date of Birth");
//out.print("\nEnter Choice: ");
//int opt = in.nextInt();
int opt = getInteger("\nEnter Choice: ");
if (opt > 0 && opt < 4) {
switch (opt) {
case 1: //name
out.print("Enter New First Name: ");
String fName = in.nextLine();
out.print("Enter New Last Name: ");
String lName = in.nextLine();
family.changeName(fName, lName, choice);
break;
case 2: //Gender
FamilyMember f = family.getFamilyMember(choice);
String gender = f.getGender();
if (f.getChildren().isEmpty()) {
gender = selectGender();
family.changeGender(gender, choice);
} else {
//swap genders
//swap mother father relationships for kids
swapGenders(f, choice);
}
break;
case 3:
String dob = enterDateOfBirth();
family.changeDOB(dob, choice);
}
} else {
out.println("Invalid Choice!");
}
}
}
private FamilyMember addMember(int option, String gender) {
out.print("Enter First Name: ");
String fName = formatString(in.nextLine().trim());
out.print("Enter Last Name: ");
String lName = formatString(in.nextLine().trim());
//String gender;
if (option != 1) { //if not adding parents
gender = selectGender();
}
String dob = enterDateOfBirth();
FamilyMember f = family.getFamilyMember(family.addMember(fName, lName, gender, dob));
f.setIndex(family.getFamilyMembers().size() - 1);
return (f);
}
private String selectGender() {
String gender = null;
out.println("Select Gender");
out.println("1. Male");
out.println("2. Female");
//out.print("Enter Choice: ");
//int gOpt = in.nextInt();
int gOpt = getInteger("Enter Choice: ");
if (gOpt == 1) {
gender = "Male";
} else if (gOpt == 2) {
gender = "Female";
} else {
out.println("Invalid Choice");
}
return gender;
}
private void swapGenders(FamilyMember f, int choice) {
String gender;
out.println("\nNOTE: Editing A Parent Nodes Gender Will Swap Parents Genders\n"
+ "And Swap Mother/Father Relationships For All Children.");
out.println("\nContinue:");
out.println("1. Yes");
out.println("2. No");
//out.print("\nEnter Choice: ");
//int select = in.nextInt();
int select = getInteger("\nEnter Choice: ");
if (select > 0 && select < 3) {
switch (select) {
case 1:
//swap relationships
gender = selectGender();
//if selected gender is different
if (!gender.equals(f.getGender())) {
//swap
String g = f.getGender();
family.changeGender(gender, choice);
family.changeGender(g, f.getPartner().getIndex());
if (g.equals("Male")) {
for (FamilyMember m : f.getChildren()) {
m.setMother(f);
m.setFather(f.getPartner());
}
} else {
for (FamilyMember m : f.getChildren()) {
m.setFather(f);
m.setMother(f.getPartner());
}
}
}
break;
case 2:
break;
}
} else {
out.println("Invalid Choice");
}
}
private String formatString(String s) {
String firstLetter = s.substring(0, 1);
String remainingLetters = s.substring(1, s.length());
s = firstLetter.toUpperCase() + remainingLetters.toLowerCase();
return s;
}
private String enterDateOfBirth() {
out.print("Enter Year Of Birth (0 - 2011): ");
String y = in.nextLine();
out.print("Enter Month Of Birth (1-12): ");
String m = in.nextLine();
if (m.trim().equals("")) {
m = "0";
}
if (Integer.parseInt(m) < 10) {
m = "0" + m;
}
m += "-";
out.print("Enter Date of Birth (1-31): ");
String d = in.nextLine();
if (d.trim().equals("")) {
d = "0";
}
if (Integer.parseInt(d) < 10) {
d = "0" + d;
}
d += "-";
String dob = d + m + y;
while (!DateValidator.isValid(dob)) {
out.println("Invalid Date. Try Again:");
dob = enterDateOfBirth();
}
return (dob);
}
private void displayAncestors() {
out.print("\nDisplay Ancestors For Which Member: ");
int choice = selectMember();
if (choice >= 0) {
FamilyMember node = family.getFamilyMember(choice);
FamilyMember ms = findRootNode(node, 0, 2, -1);
FamilyMember fs = findRootNode(node, 1, 2, -1);
out.println("\nPrint Ancestors");
out.println("\nMothers Side");
if(ms==null){
out.println("Member has no mother");
}else{
printDescendants(ms, node, ms.getGeneration());
}
out.println("\nFathers Side");
if(fs==null){
out.println("Member has no father");
}else{
printDescendants(fs, node, fs.getGeneration());
}
} else {
out.println("Invalid Option!");
}
}
private void displayDescendants() {
out.print("\nDisplay Descendants For Which Member: ");
int choice = selectMember();
if (choice >= 0) {
FamilyMember node = family.getFamilyMember(choice);
out.println("\nPrint Descendants");
printDescendants(node, null, 0);
} else {
out.println("Invalid Option!");
}
}
private FamilyMember findRootNode(FamilyMember node, int parent, int numGenerations, int count) {
FamilyMember root;
count++;
if (count < numGenerations) {
if (parent == 0) {
if(node.hasMother()){
node = node.getMother();
}else{
return node;
}
} else {
if(node.hasFather()){
node = node.getFather();
}else{
return node;
}
}
root = findRootNode(node, 1, numGenerations, count);
return root;
}
return node;
}
private int findHighestLeafGeneration(FamilyMember node) {
int gen = node.getGeneration();
for (int i = 0; i < node.getChildren().size(); i++) {
int highestChild = findHighestLeafGeneration(node.getChild(i));
if (highestChild > gen) {
gen = highestChild;
}
}
return gen;
}
private void printDescendants(FamilyMember root, FamilyMember node, int gen) {
out.print((root.getGeneration() + 1) + " " + root.getFullName());
out.print(" [" + root.getDob() + "] ");
if (root.getPartner() != null) {
out.print("+Partner: " + root.getPartner().getFullName() + " [" + root.getPartner().getDob() + "] ");
}
if (root == node) {
out.print("*");
}
out.println();
if (!root.getChildren().isEmpty() && root != node) {
for (int i = 0; i < root.getChildren().size(); i++) {
for (int j = 0; j < root.getChild(i).getGeneration() - gen; j++) {
out.print(" ");
}
printDescendants(root.getChild(i), node, gen);
}
} else {
return;
}
}
//retrieve highest generation
public int getRootGeneration() {
int min = family.getFamilyMember(0).getGeneration();
for (int i = 0; i < family.getFamilyMembers().size(); i++) {
min = Math.min(min, family.getFamilyMember(i).getGeneration());
}
return Math.abs(min);
}
public void sortGenerations() {
int amount = getRootGeneration();
for (FamilyMember member : family.getFamilyMembers()) {
member.setGeneration(member.getGeneration() + amount);
}
}
//test method - temporary
private void initialise() {
family.addMember("Bart", "Simpson", "Male", "18-03-1985");
family.getFamilyMember(0).setIndex(0);
family.addMember("Homer", "Simpson", "Male", "24-09-1957");
family.getFamilyMember(1).setIndex(1);
family.addMember("Marge", "Simpson", "Female", "20-07-1960");
family.getFamilyMember(2).setIndex(2);
family.addMember("Lisa", "Simpson", "Female", "28-01-1991");
family.getFamilyMember(3).setIndex(3);
family.addMember("Abe", "Simpson", "Male", "10-03-1920");
family.getFamilyMember(4).setIndex(4);
family.addMember("Mona", "Simpson", "Female", "18-09-1921");
family.getFamilyMember(5).setIndex(5);
//set relationships
family.getFamilyMember(0).setMother(family.getFamilyMember(2));
family.getFamilyMember(0).setFather(family.getFamilyMember(1));
family.getFamilyMember(3).setMother(family.getFamilyMember(2));
family.getFamilyMember(3).setFather(family.getFamilyMember(1));
family.getFamilyMember(1).addChild(family.getFamilyMember(3));
family.getFamilyMember(1).addChild(family.getFamilyMember(0));
family.getFamilyMember(2).addChild(family.getFamilyMember(3));
family.getFamilyMember(2).addChild(family.getFamilyMember(0));
family.getFamilyMember(1).setPartner(family.getFamilyMember(2));
family.getFamilyMember(2).setPartner(family.getFamilyMember(1));
family.getFamilyMember(4).setPartner(family.getFamilyMember(5));
family.getFamilyMember(5).setPartner(family.getFamilyMember(4));
family.getFamilyMember(1).setMother(family.getFamilyMember(5));
family.getFamilyMember(1).setFather(family.getFamilyMember(4));
family.getFamilyMember(4).addChild(family.getFamilyMember(1));
family.getFamilyMember(5).addChild(family.getFamilyMember(1));
family.getFamilyMember(0).setGeneration(2);
family.getFamilyMember(1).setGeneration(1);
family.getFamilyMember(2).setGeneration(1);
family.getFamilyMember(3).setGeneration(2);
family.getFamilyMember(4).setGeneration(0);
family.getFamilyMember(5).setGeneration(0);
}
}
All tasks require the same effort. It will always go like this:
public void deleteFamilyMember(FamilyMember member) {
member.mother.children.remove(member);
member.father.children.remove(member);
member.partner.children.remove(member);
for (FamilyMember child:children) {
if (child.father == member) child.father = null;
if (child.mother == member) child.mother = null;
if (child.partner == member) child.partner = null;
}
// now all references to this member are eliminated, gc will do the rest.
}
Example:
Homer.mother = ??
Homer.father = ??
Homer.partner = Marge
Homer.children = {Bart, Lisa, Maggie}
Marge.mother = ??
Marge.father = ??
Marge.partner = Homer
Marge.children = {Bart, Lisa, Maggie}
Bart.mother = Marge
Bart.father = Homer
Bart.partner = null
Bart.children = {}
Lisa.mother = Marge
Lisa.father = Homer
Lisa.partner = null
Lisa.children = {}
Maggie.mother = Marge
Maggie.father = Homer
Maggie.partner = null
Maggie.children = {}
To remove Bart from the familiy tree, we should set Bart's mother and father attribute to null and need to remove Bart from Homer's and Marge's list of children.
To remove Marge, we have to set her partner's partner to null (Homer.partner) and visit all children to clear their mother attribute (that's this child.mother part of the code above)
I would model things differently and do the work in the FamilyMember class. Here's a sample implementation:
public class FamilyMember{
public enum Gender{
MALE, FEMALE
}
private final Set<FamilyMember> exPartners =
new LinkedHashSet<FamilyMember>();
public Set<FamilyMember> getExPartners(){
return new LinkedHashSet<FamilyMember>(exPartners);
}
public FamilyMember getFather(){
return father;
}
public FamilyMember getMother(){
return mother;
}
public Set<FamilyMember> getSiblings(){
final Set<FamilyMember> set =
father == null && mother == null ? Collections
.<FamilyMember> emptySet() : new HashSet<FamilyMember>();
if(father != null){
set.addAll(father.children);
}
if(mother != null){
set.addAll(mother.children);
}
set.remove(this);
return set;
}
public String getName(){
return name;
}
private final Gender gender;
private FamilyMember partner;
private final FamilyMember father;
private final FamilyMember mother;
private final Set<FamilyMember> children =
new LinkedHashSet<FamilyMember>();
private final String name;
public FamilyMember haveChild(final String name, final Gender gender){
if(partner == null){
throw new IllegalStateException("Partner needed");
}
final FamilyMember father = gender == Gender.MALE ? this : partner;
final FamilyMember mother = father == this ? partner : this;
return new FamilyMember(father, mother, name, gender);
}
public Set<FamilyMember> getChildren(){
return new LinkedHashSet<FamilyMember>(children);
}
#Override
public String toString(){
return "[" + name + ", " + gender + "]";
}
public FamilyMember(final String name, final Gender gender){
this(null, null, name, gender);
}
public FamilyMember(final FamilyMember father,
final FamilyMember mother,
final String name,
final Gender gender){
if(name == null){
throw new IllegalArgumentException("A kid needs a name!");
}
if(gender == null){
throw new IllegalArgumentException("Which is it going to be?");
}
this.father = father;
this.name = name;
this.gender = gender;
if(father != null){
father.children.add(this);
}
this.mother = mother;
if(mother != null){
mother.children.add(this);
}
}
public FamilyMember hookUpWith(final FamilyMember partner){
if(partner.gender == gender){
throw new IllegalArgumentException(
"Sorry, same-sex-marriage would make things too complicated");
}
this.partner = partner;
partner.partner = this;
return this;
}
public FamilyMember splitUp(){
if(partner == null){
throw new IllegalArgumentException("Hey, I don't have a partner");
} else{
partner.partner = null;
exPartners.add(partner);
partner.exPartners.add(this);
partner = null;
}
return this;
}
public FamilyMember getPartner(){
return partner;
}
}
And here's the much more expressive code you can write that way:
FamilyMember marge = new FamilyMember("Marge", Gender.FEMALE);
FamilyMember homer = new FamilyMember("Homer", Gender.MALE);
homer.hookUpWith(marge);
FamilyMember bart = homer.haveChild("Bart", Gender.MALE);
FamilyMember lisa = marge.haveChild("Lisa", Gender.FEMALE);
System.out.println("Homer & Marge: " + marge + ", "
+ marge.getPartner());
homer.splitUp();
FamilyMember dolores =
marge
.hookUpWith(new FamilyMember("New Guy", Gender.MALE))
.haveChild("Dolores", Gender.FEMALE);
FamilyMember bruno =
homer
.hookUpWith(new FamilyMember("New Girl", Gender.FEMALE))
.haveChild("Bruno", Gender.MALE);
System.out.println(
"Marge & Partner: " + marge + ", " + marge.getPartner());
System.out.println("Marge's Ex-Partners: " + marge.getExPartners());
System.out.println(
"Homer & Partner: " + homer + ", " + homer.getPartner());
System.out.println("Homer's Ex-Partners: " + homer.getExPartners());
System.out.println("Marge's kids: " + marge.getChildren());
System.out.println("Homer's kids: " + homer.getChildren());
System.out.println("Dolores's siblings: " + dolores.getSiblings());
System.out.println("Brunos's siblings: " + bruno.getSiblings());
Output:
Homer & Marge: [Marge, FEMALE], [Homer, MALE]
Marge & Partner: [Marge, FEMALE], [New Guy, MALE]
Marge's Ex-Partners: [[Homer, MALE]]
Homer & Partner: [Homer, MALE], [New Girl, FEMALE]
Homer's Ex-Partners: [[Marge, FEMALE]]
Marge's kids: [[Bart, MALE], [Lisa, FEMALE], [Dolores, FEMALE]]
Homer's kids: [[Bart, MALE], [Lisa, FEMALE], [Bruno, MALE]]
Dolores's siblings: [[Bart, MALE], [Lisa, FEMALE]]
Brunos's siblings: [[Bart, MALE], [Lisa, FEMALE]]