Program will not print the statement - java

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;
}

Related

How to search an array for a value?

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

ArrayIndexOutOfBounds Exception Error When Displaying Reservations After Booking - Java

I'm making a reservation feature for my events, and I can successfully add the attendee, however when I want to display the details for every attendee, it gives me a ArrayIndexOutOfBounds exception error, which I'm not quite sure how to fix.
Main.java
private static Scanner sc = new Scanner(System.in);
private static int eventCreationLimit = 5;
private static Event[] events = new Event[eventCreationLimit];
private static int eventsCreated;
public static void main(String args[]) {
String input;
// Main menu.
do {
System.out.println("\n~ BOOKING SYSTEM ~");
System.out.println("------------------");
System.out.println("A. Schedule an Event");
System.out.println("B. Add an Attendee");
System.out.println("C. View Reservations");
System.out.println("X. Exit\n");
System.out.print("Select an option: ");
input = sc.nextLine();
switch (input.toUpperCase()) {
case "A":
scheduleAnEvent();
break;
case "B":
addAttendee();
break;
case "C":
displayReservations();
break;
case "X":
System.out.println("INFO: You have exited the booking system.");
break;
default:
System.out.println("ERROR: Invalid input!");
}
} while (!input.equalsIgnoreCase("X"));
}
private static void scheduleAnEvent() {
System.out.println("\n~ SCHEDULE A EVENT ~");
System.out.println("--------------------");
System.out.print("Enter the ID: ");
String ID = sc.nextLine();
...
System.out.print("Enter the attendee limit: ");
int attendeeLimit = Integer.parseInt(sc.nextLine());
// Add the new event to the array.
events[eventsCreated++] = new Event(ID, ..., attendeeLimit, attendeeLimit, ...);
for (int i = 0; i < eventsCreated; i++)
// Set the places available for the specific event being created to subtract it later when an attendee is added.
if (ID.equals(events[i].getID()))
// The number of places available left in the event can be displayed by going to "B. View All Events".
events[i].setPlacesAvailable(attendeeLimit);
// Give the user a confirmation message.
System.out.println("\nINFO: Sucessfully created Event: " + ID + ".");
}
private static void addAttendee() {
Event event = null;
boolean result = false;
System.out.println("\n~ ADD AN ATTENDEE ~");
System.out.println("-------------------");
System.out.print("Enter attendee name: ");
String name = sc.nextLine();
System.out.print("Enter attendee phone number: ");
String phone = sc.nextLine();
Attendee a = new Attendee(name, phone);
System.out.print("Enter event ID: ");
String eventID = sc.nextLine();
// Check if the given ID matches an event.
for (int i = 0; i < eventsCreated; i++)
if (events[i].getID().equals(eventID))
event = events[i];
if (event != null) {
if (event.getID().equals(eventID)) {
result = ((Event) event).addAttendee(a);
if (result) {
// If the event has enough room, then add the attendee.
System.out.println("INFO: Attendee successfully added to Event: " + eventID + ".");
displayReservations();
}
else
// If the event is full, then the attendee will not be added.
System.out.println("ERROR: The Event: " + eventID + " is full, the attendee could not be added.");
} else
System.out.println("ERROR: The given ID does not match any existing event.");
} else
System.out.println("ERROR: The event was not found.");
}
private static void displayReservations() {
System.out.println("\n~ RESERVATIONS ~");
System.out.println("----------------");
String pattern = "%-18s %-18s %-22s %-1s\n";
System.out.printf(pattern, "NAME", "PHONE", "EVENT ID", "FEE");
System.out.println("----------------------------------------------------------------");
// Display all reservations for events.
for (int i = 0; i < events[i].getAttendeeCount(); i++)
events[i].displayReservations();
}
Event.java
...
private String ID;
private int attendeeLimit;
private int attendeeCount;
private int placesAvailable;
private Attendee[] a = new Attendee[attendeeCount];
public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
this.ID = ID;
this.placesAvailable = placesAvailable;
this.attendeeLimit = attendeeLimit;
}
public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }
public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }
public boolean addAttendee(Attendee at) {
// Proceed to add the attendee if there is enough room.
if (attendeeCount <= placesAvailable) {
attendeeCount++;
// Decrease the number of places available by one.
setPlacesAvailable(placesAvailable - 1);
return true;
}
return false;
}
public void displayReservations() {
System.out.println("ID: " + ID);
if (attendeeCount > 0)
for (int i = 0; i < attendeeCount; i++)
a[i].attendeeDetails();
}
Attendee.java
private String name;
private String phone;
public Attendee(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() { return this.name; }
public String getPhone() { return this.phone; }
public void attendeeDetails() {
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
}
The above code gives me a ArrayIndexOutOfBoundsException error in the displayReservations() method (a[i].attendeeDetails()) whenever I try to add an attendee to an event.
Problem: How do I display all reservation details for all events? Thank you for your help!
EDIT
The error:
Index 0 out of bounds for length 0.
There are a couple of issues with your code:
You are maintaining an attendeeCount separately than the size of the Attendee[], but in your addAttendee() method, you never actually add the new Attendee to the array
Because Attendee[] is an array, it can't grow larger than the size when first initialized. If you want to use an array, instead of an ArrayList that can grow dynamically, you need to initialize the array to the maximum size: placesAvailable:
So, my recommendation would be to switch from using an array to an ArrayList by importing java.util.Arraylist, changing the declaration of the Attendee[] to an ArrayList, and updating the rest of the Event.java code to use the ArrayList, as well as making sure you add the new Attendee in the addAttendee() method. Finally, you don't need to maintain the attendee count separately, just ask the attendees ArrayList it's current size.
Event.java
...
import java.util.*; //You can import all java.util classes
private String ID;
private int attendeeLimit;
private int placesAvailable;
private List<Attendee> attendees = new ArrayList<>(); //Initialize the attendees ArrayList
public Demonstration(..., String ID, int placesAvailable, int attendeeLimit, ...) {
this.ID = ID;
this.placesAvailable = placesAvailable;
this.attendeeLimit = attendeeLimit;
}
public String getID() { return this.ID; }
public int getPlacesAvailable() { return this.placesAvailable; }
public int getAttendeeLimit() { return this.attendeeLimit; }
public void setPlacesAvailable(int placesAvailable) { this.placesAvailable = placesAvailable; }
public boolean addAttendee(Attendee at) {
// Proceed to add the attendee if there is enough room.
if (attendeeCount <= placesAvailable) {
attendees.add(at); //Make sure you add the new Attendee to the list
// Decrease the number of places available by one.
setPlacesAvailable(placesAvailable - 1);
return true;
}
return false;
}
public void displayReservations() {
System.out.println("ID: " + ID);
int attendeeCount = attendees.size(); //Calculate the number of Attendees
if (attendeeCount > 0)
for (int i = 0; i < attendeeCount; i++)
attendees.get(i).attendeeDetails();
}
attendeCount does not have a value as at the time you creating the Array "a". For what you are trying to achieve, I suggest:
i. Use an Arraylist.
ii. Initialize you array in the constructor to attendeLimit.
If possible, I also suggest you use parameter methods where neccessary.

how to read data from arraylist that is inside linkedlist

I have an arraylist of year and value. this arraylist is place in a linkedlist as one of element in the linkedlist.
linkedlist elements -> countrycode, indicatorName, indicatorCode and data (arraylist)
how can i retrieve the value from the arraylist when i search for the indicator code and then the year?
segments of my code from application class:
while(str2 != null ){
StringTokenizer st = new StringTokenizer(str2,";");
ArrayList <MyData> data = new ArrayList();
String cCode = st.nextToken();
String iName = st.nextToken();
String iCode = st.nextToken();
for (int j = 0; j < 59; j++){
String v = st.nextToken();
int year = 1960 + j;
d1 = new MyData (year,v);
data.add(d1);
}
Indicator idct1 = new Indicator (cCode,iName,iCode,data);
bigdata.insertAtBack(idct1);
str2 = br2.readLine();
}
//search
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(bigdata,search3);
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
public static void searchYear (myLinkedList bigdata, int searchTerm) {
Indicator idct4 = (Indicator)bigdata.getFirst();
boolean found = false;
while(idct4 != null){
if(idct4.getDYear() == searchTerm) {
found = true;
System.out.println(idct4.getDValue());
}
idct4 = (Indicator)bigdata.getNext();
}
if (!found){
String message = "Error!";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",JOptionPane.ERROR_MESSAGE);
}
}
indicator class:
public Indicator(String cCode, String iName, String iCode,ArrayList <MyData> DataList){
this.cCode = cCode;
this.iName = iName;
this.iCode = iCode;
this.DataList = DataList;
}
public String getCCode(){return cCode;}
public String getIName(){return iName;}
public String getICode(){return iCode;}
public int getDYear(){return d.getYear();}
public String getDValue(){return d.getValue();}
public void setCCode(String cCode){this.cCode = cCode;}
public void setIName(String iName){this.iName = iName;}
public void setICode(String iCode){this.iCode = iCode;}
public String toString(){
return (cCode + "\t" + iName + "\t" + iCode + "\t" + DataList.toString());
}
}
MyData class:
public MyData(int year, String value){
this.year = year;
this.value = value;
}
public int getYear(){return year;}
public String getValue(){return value;}
public void setYear(int year){this.year = year;}
public void setValue(String value){this.value = value;}
public String toString(){
return (value + "(" + year + ")");
}
I can't add a comment yet, but here's what I'm assuming.
Here it's getting a matching Indicator code (iCode), so let's pass the Indicator object (idct3) into searchYear method instead to focus on its ArrayList < MyData > DataList:
String search2 = JOptionPane.showInputDialog("Enter Indicator Code");
boolean found2 = false;
Indicator idct3 = (Indicator)bigdata.getFirst();
while (idct3 != null){
if ( idct3.getICode().equalsIgnoreCase(search2)){
int search3 = Integer.parseInt(JOptionPane.showInputDialog("Enter year"));
found2 = true;
searchYear(idct3,search3); // Indicator passed in here
}
if (!found2) {
System.out.println("Indicator Code is not in the data");
}
idct3 = (Indicator)bigdata.getNext();
}
Let's change searchYear method to take the Indicator class and search its DataList:
public static void searchYear (Indicator indicator, int searchTerm) {
for (int i = 0; i < indicator.DataList.size(); i++) {
if (indicator.DataList.get(i).getYear() == searchTerm) { // Sequentially get MyData object from DataList and its year for comparison
System.out.println("Found year " + searchTerm + " with Indicator code " + indicator.getICode() + " having value " + indicator.DataList.get(i).getValue());
return; // Exit this method
}
}
System.out.println("Not Found");
}

toString an arraylist containing object

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) + "]"
}

Infinite while loop in java, not reading in sentinel

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.

Categories