Related
Hello and thank you for your time in advanced.
I am trying to create a few different football leagues (e.g. the Italian national league (Serie A ), the English national league (Premier league), ... , second division Italian league (Serie B), etc).
Right now I'm trying to figure out what's the best way to separate clubs of different country's so that a Italian club cant compete in a Spanish league and vice versa.
As of now I have created the Player, PlayerBuilder, Team and TeamBuilder classes.
public class FootBallClub {
private String name;
private String stadium;
private String mainCoach;
private String secondCoach;
private ArrayList<FootballPlayer> playerList;
private ArrayList Matches;
private String county;
private int gamesPlayed;
private int gamesWon;
private int gamesDrawn;
private int gamesLost;
private int goalsScored;
private int goalsConceded;
private FootballPlayer topGoalScorer;
public FootBallClub() {
}
public void addPlayer(FootballPlayer player) {
playerList.add(player);
}
public void addPlayers (ArrayList<FootballPlayer> players) {
for (FootballPlayer player: players){
playerList.add(player);
}
}
public ArrayList<FootballPlayer> getPlayerList() {
ArrayList<FootballPlayer> players = new ArrayList<>();
for (FootballPlayer player : players) {
try {
players.add(player.clone());
} catch (CloneNotSupportedException e) {
System.out.println("Football Player " + player.getName() + " could not be cloned");
System.out.println(e.getStackTrace());
}
}
return players;
}
// getters and setters for all the fields
public static ArrayList<FootballPlayer> createTeam(){
String first = "Liam,Noah,Oliver,Elijah,William,James,Benjamin,Lucas,Henry,Alexander,Mason,Michael,Ethan,Daniel,Jacob,Logan,Jackson,Levi,Sebastian,Mateo,Jack,Owen,Theodore,Aiden,Samuel,Joseph,John,David,Wyatt,Matthew,Luke,Asher,Carter,Julian,Grayson,Leo,Jayden,Gabriel,Isaac,Lincoln,Anthony,Hudson,Dylan,Ezra,Thomas";
String [] firstNames = first.split(",");
String last = "Smith,Johnson,Williams,Brown,Jones,Garcia,Miller,Davis,Rodriguez,Martinez,Hernandez,Lopez,Gonzalez,Wilson,Anderson,Thomas,Taylor,Moore,Jackson,Martin,Lee,Perez,Thompson,White,Harris,Sanchez,Clark,Ramirez,Lewis,Robinson,Walker,Young,Allen,King,Wright,Scott,Torres,Nguyen,Hill,Flores,Green,Adams,Nelson,Baker,Hall,Rivera,Campbell,Mitchell,Carter,Roberts,Gomez,Phillips,Evans,Turner,Diaz,Parker,Cruz,Edwards,Collins,Reyes,Stewart,Morris,Morales,Murphy,Cook,Rogers,Gutierrez,Ortiz,Morgan,Cooper,Peterson,Bailey,Reed,Kelly,Howard,Ramos,Kim,Cox,Ward,Richardson,Watson,Brooks,Chavez,Wood,James,Bennett,Gray,Mendoza,Ruiz,Hughes,Price,Alvarez,Castillo,Sanders,Patel,Myers,Long,Ross,Foster,Jimenez,Powell,Jenkins,Perry,Russell,Sullivan,Bell,Coleman,Butler,Henderson,Barnes,Gonzales,Fisher,Vasquez,Simmons,Romero,Jordan,Patterson,Alexander,Hamilton,Graham,Reynolds,Griffin,Wallace,Moreno,West,Cole,Hayes,Bryant,Herrera,Gibson,Ellis,Tran,Medina,Aguilar,Stevens,Murray,Ford,Castro,Marshall,Owens,Harrison,Fernandez,Mcdonald,Woods,Washington,Kennedy,Wells,Vargas,Henry,Chen,Freeman,Webb,Tucker,Guzman,Burns,Crawford,Olson,Simpson,Porter,Hunter,Gordon,Mendez,Silva,Shaw,Snyder,Mason,Dixon,Munoz,Hunt,Hicks,Holmes,Palmer,Wagner,Black,Robertson,Boyd,Rose,Stone,Salazar,Fox,Warren,Mills,Meyer,Rice,Schmidt,Garza,Daniels";
String [] lastNames = last.split(",");
Random random = new Random();
final List<FootballPosition> footballPositions = Collections.unmodifiableList(Arrays.asList(FootballPosition.values()));
final List<DominantSide> sides = Collections.unmodifiableList(Arrays.asList(DominantSide.values()));
ArrayList<FootballPlayer> footballPlayers = new ArrayList<FootballPlayer>();
for (int i =0; i<footballPositions.size() ; i++) {
String randomeName = firstNames[random.nextInt(1000)]+ " "+ lastNames[random.nextInt(1000)];
int randomAge = 18 + random.nextInt(23);
int randomHeight = 165 + random.nextInt(30);
int randomWeight = (int) ((randomHeight - 100) * 0.85 + random.nextInt(25));
DominantSide randomSide = sides.get(random.nextInt(3));
boolean isHealthy = true;
int randomSalary = 700000 + random.nextInt(5000000);
FootballPosition primaryPosition = footballPositions.get(i);
List<FootballPosition> allPosition = new ArrayList<FootballPosition>();
allPosition.add(primaryPosition);
EnumSet set = EnumSet.noneOf(FootballPosition.class);
for (int j = 0; j < random.nextInt(4); j++) {
FootballPosition newPosition = footballPositions.get(random.nextInt(footballPositions.size()));
if(allPosition.contains(newPosition)){
i--;
}
set.add(newPosition);
}
FootballPlayer randomPlayer = new FootballPlayerBuilder()
.setName(randomeName)
.setAge(randomAge)
.setHeight(randomHeight)
.setWeight(randomWeight)
.setDominantSide(randomSide)
.setIsHealthy(isHealthy)
.setSalary(randomSalary)
.setPrimaryPosition(primaryPosition)
.setSecondaryPositions(set)
.build();
footballPlayers.add(randomPlayer);
}
return footballPlayers;
}
}
public class FootballPlayer {
private String name;
private FootballPosition primaryPosition;
private EnumSet<FootballPosition> secondaryPositions;
private double height;
private double weight;
private int age;
private Enum dominantSide;
private boolean isHealthy;
private int salary;
public FootballPlayer() {
}
// getters and setters for all the fields
#Override
public String toString() {
return "FootballPlayer{" +
"name='" + name + '\'' +
", primaryPosition=" + primaryPosition +
", secondaryPositions=" + secondaryPositions +
", height=" + height +
", weight=" + weight +
", age=" + age +
", dominantSide=" + dominantSide +
", isHealthy=" + isHealthy +
", salary=" + salary +
'}';
}
#Override
public FootballPlayer clone() throws CloneNotSupportedException {
FootballPlayer clone = new FootballPlayerBuilder()
.setName(this.name)
.setAge(this.age)
.setHeight((int) this.height)
.setWeight((int) this.weight)
.setDominantSide(this.dominantSide)
.setIsHealthy(this.isHealthy)
.setSalary(this.salary)
.setPrimaryPosition(this.primaryPosition)
.setSecondaryPositions(this.secondaryPositions)
.build();
return clone;
}
}
Player and Team simply hold information about the player and team through their field and the builders build the objects.
None of the classes implement or extend any classes.
My question is : What's the best way implementing the League class so that a league from a certain county only accepts teams form the same country.
Should I save a string, int, enum ..., on the team class and check before adding to the league table? Is the a clever way to use interfaces to salve this problem?
Consider making an enum, it is definitely better than a generic string:
enum Country {
Spain,
Germany,
UK
}
Each league may contain a HashSet<FootBallClub>. So, you can put football clubs into leagues as you want.
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();
}
}
}
}
I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}
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) + "]"
}
A briefing of the program: This program keeps track of people who have airline membership cards and how many points they collect each week. (week1, 2, 3, 4) The information is stored in the array, which then when needed, can be outputted by pressing the "listButton".
I know how to grab a value from the array and simply output it, but unsure how to do so with a loop. See problem area under "totalPointsButton"
public class AirlineCardsView extends FrameView {
class airline {
String lastName, firstName;
int week1, week2, week3, week4;
airline (int _week1, int _week2, int _week3, int _week4, String _lastName, String _firstName) {
week1 = _week1;
week2 = _week2;
week3 = _week3;
week4 = _week4;
lastName = _lastName;
firstName = _firstName;
}
}
/** Define the ArrayList */
ArrayList <airline> members = new ArrayList <airline>();
public AirlineCardsView(SingleFrameApplication app) {
//GUI stuff
}// </editor-fold>
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String lastName, firstName;
int week1, week2, week3, week4;
week1 = Integer.parseInt(weekOneField.getText());
week2 = Integer.parseInt(weekTwoField.getText());
week3 = Integer.parseInt(weekThreeField.getText());
week4 = Integer.parseInt(weekFourField.getText());
lastName = lastNameField.getText();
firstName = firstNameField.getText();
airline c = new airline(week1, week2, week3, week4, firstName, lastName);
members.add(c);
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp = "";
for (int x=0; x<=members.size()-1; x++) {
temp = temp + members.get(x).firstName + " "
+ members.get(x).lastName + ": "
+ members.get(x).week1 + " "
+ members.get(x).week2 + " "
+ members.get(x).week3 + " "
+ members.get(x).week4 + "\n";
}
memberListTArea.setText(temp);
}
Here I'm unsure how to initialize the values week1, week2, week3, week4 (for int totalPoints) with the same values stored in the array for the corresponding member.
private void totalPointsButtonActionPerformed(java.awt.event.ActionEvent evt) {
int week1, week2, week3, week4;
String lastName, firstName;
String points = "";
for (int j = 0; j < members.size()-1; j++) {
//this line checks the inputted name to see if it matches any stored in array.
if (members.get(j).lastName.equals(lastNameField.getText())) {
int totalPoints = week1 + week2 + week3 + week4; //then adds total points
}
}
}
I hope I understood the question correctly....
firstly, this line has problem:
for (int j = 0; j < members.size()-1; j++) {
you should remove the -1 or use <=. otherwise you won't reach the last element.
the if (members.get(j).lastName.equals(lastNameField.getText())) may throw NPE. (members.get(j).lastName could be null) also the variables defined in this method (week1-4, and the lastname, firstname) don't make much sense.
you declare the int totalPoints in if block, which means, it won't be seen outside the if block. It is not big deal, if all your logic is in if block.
you could try:
Airline al = null;
int totalPoints;
for (int j = 0; j < members.size(); j++) {
al = members.get(j);
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
even better:
int totalPoints;
for (Airline al:members) {
if (al.lastName.equals(lastNameField.getText())) {
totalPoints = al.week1 + al.week2 + al.week3 + al.week4;
}
}
to make the codes look better, you could consider add getter/setters in your Airline class. also add a method, int getTotalPoints() return the sum of 4 weeks. Then you don't have to sum it outside the class.
You should add get and set methods to your airline class. So when you store an object of airline in the arraylist you can get their values by using "members.get(j).week1, members.get(j).week2, etc"
For example create your airline class like this.
public class airline {
String lastName;
String firstName;
int week1;
int week2;
int week3;
int week4;
public airline (int week1, int week2, int week3, int week4, String lastName, String firstName) {
week1 = this.week1;
week2 = this.week2;
week3 = this.week3;
week4 = this.week4;
lastName = this.lastName;
firstName = this.firstName;
}
public int getWeek1(){
return week1;
}
public void setWeek1(int newWeek1){
week1 = newWeek1;
}
public int getWeek2(){
return week2;
}
public void setWeek2(int newWeek2){
week2 = newWeek2;
}
public int getWeek3(){
return week3;
}
public void setWeek3(int newWeek3){
week3 = newWeek3;
}
public int getWeek4(){
return week4;
}
public void setWeek4(int newWeek4){
week4 = newWeek4;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String newFirstName){
firstName = newFirstName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String newLastName){
lastName = newLastName;
}
public String toString(){
return getWeek1() + " " + getWeek2() + " " + getWeek3() + " " + getWeek4() + getFirstName() + " " + getLastName();
}
}