ClassCastException in BookingApp - java

I'm getting a ClassCastException at:
RVBooking rvbooking = (RVBooking) bookingList.get(iweight);
I want to store the user's weightvehicle input and invoke the recordWeight() method. Sorry if i am not explaining this clearly. Thanks in advance.
Stack Trace
FerryBookingSystem [Java Application]
bookingSystem.FerryBookingSystem at localhost:51019
Thread [main] (Suspended (exception ClassCastException))
FerryBookingSystem.recordVehicleWeight() line: 144
FerryBookingSystem.main(String[]) line: 191
C:\Program Files\Java\jre7\bin\javaw.exe (16/05/2013 12:42:10 AM)
BookingException
class BookingException extends Exception{
String message;
String IDs;
public BookingException(String message){
this.message = message;
}
public BookingException(String message, String IDs){
this.message = message;
this.IDs = IDs;
}
public String getIDs(){
return IDs;
}
public String getMessage(){
return message;
}
}
FerryBookingSystem Class
public class FerryBookingSystem {
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
private static ArrayList<RVBooking> rvbookingList = new ArrayList<RVBooking>();
private static Scanner userInput = new Scanner (System.in);
public static int bookingIDExists(String IDs){
if (bookingList.size() == -1){
return -1;
}
for (int i = 0; i < bookingList.size(); i++){
if(bookingList.get(i).getbookingID().equals(IDs)){
return i;
}
}
return -1;
}
public static int rvbookingIDExists(String IDs){
if (rvbookingList.size() == -1){
return -1;
}
for(int i = 0; i < rvbookingList.size(); i++){
if(rvbookingList.get(i).getbookingID().equals(IDs)){
return i;
}
}
return -1;
}
public static boolean recordVehicleWeight(){
String booking_ID;
double weight = 0;
int iweight = 0;
System.out.print("Please enter the booking ID: ");
booking_ID = userInput.nextLine();
if(bookingIDExists(booking_ID) != -1){
if(rvbookingIDExists(booking_ID) != 1){
RVBooking rvbooking = (RVBooking) bookingList.get(iweight);
System.out.print("Please enter the weight of the vehicle: ");
weight = userInput.nextDouble();
iweight = (int)weight;
rvbooking.recordWeight(iweight);
return true;
}
else{
System.out.println("Error - cannot record weight for vehicle booking!");
return false;
}
}
else{
System.out.println("The booking ID does not exist, Please try again.");
return false;
}
}
public static void main (String [] args) throws IOException{
char user;
do{
System.out.println("**** Ferry Ticketing System ****");
System.out.println(" A - Add Vehicle Booking");
System.out.println(" B - Add Recreational Vehicle Booking");
System.out.println(" C - Display Booking Summary");
System.out.println(" D - Update Insurance Status");
System.out.println(" E - Record Recreational Vehicle Weight");
System.out.println(" F - Compile Vehicle Manifest");
System.out.println(" X - Exit");
System.out.print("Enter your selection: ");
String choice = userInput.nextLine().toUpperCase();
user = choice.length() > 0 ? choice.charAt(0) : '\n';
if (choice.trim().toString().length()!=0){
switch (user){
case 'A':
addVehicleBooking();
break;
case 'B':
addRecreationalVehicleBooking();
break;
case 'C':
displayBookingSummary();
break;
case 'D':
updateInsuranceStatus();
break;
case 'E':
recordVehicleWeight();
break;
case 'F':
break;
case 'X':
break;
default:
break;
}
}
}while(user!='X');
}
}

You are trying to cast RVBooking type to object from VehicleBooking list

Looks like your bookingList is meant to store objects of type VehicleBooking, and you are trying to cast that object to RVBooking while getting from the list
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
unless RVBooking is super class of VehicleBooking, VehicleBooking cannot be cast to RVBooking

Related

Create single array int[] attractions in Attraction class and add createAttraction() from main class to it max of 5 to be stored otherwise full

public class Attraction {
String description;
private String contactDetails;
private String guide;
private String rating;
private final double noTicketsSold = 0;
private int maxGroupSize;
private int amountActivities;
private double ticketCost;
private int uniqueID;
private static int count;
private char chosen;
private String[] storedActivities;
private static int id_counter = 0;
private final int MAX_NUM_ATTRACTIONS = 5;
private static int[] attractions;
public Attraction(int MAX_NUM_ATTRACTIONS) {
id_counter++;
attractions = new int[MAX_NUM_ATTRACTIONS];
count = 0;
}
public int getUniqueID() {
return this.uniqueID;
}
public void recordAttraction() {
if (count == attractions.length) {
System.out.println("Attractions are full");
return;
}
if (count < attractions.length) {
attractions[count] =
count++;
}
}
public Attraction(char chosen, String description, double ticketCost, int maxGroupSize, String contactDetails,
int amountActivities, String[] storedActivities) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.maxGroupSize = maxGroupSize;
this.contactDetails = contactDetails;
this.amountActivities = amountActivities;
this.storedActivities = storedActivities;
}
public Attraction(char chosen, String description, double ticketCost, String guide, String rating) {
count++;
id_counter++;
this.chosen = chosen;
this.description = description;
this.ticketCost = ticketCost;
this.guide = guide;
this.rating = rating;
}
public void displayAllDetails() {
System.out.printf("\nID : %d%n", getUniqueID());
System.out.printf("Description : %s%n", description);
System.out.printf("Ticket cost : $%.2f%n", ticketCost);
System.out.printf("Tickets sold : %.0f%n", noTicketsSold);
if (chosen == 'y') {
System.out.println("Activity :");
int i = 0;
while (amountActivities > i) {
System.out.println(" : " + storedActivities[i]);
i++;
}
System.out.printf("Max Attendees : %d%n", maxGroupSize);
System.out.printf("Agency : %s%n", contactDetails);
}
if (chosen == 'n') {
System.out.printf("Instruction guide : %s%n", guide);
System.out.printf("Difficulty : %s%n", rating);
}
}
}
import java.util.Scanner;
public class StageA {
private static final Scanner sc = new Scanner(System.in);
private Attraction attractions = null;
public static void main(String[] args) {
StageA a = new StageA();
a.runMenu();
}
private void runMenu() {
char selection;
do {
displayMenu();
selection = sc.nextLine().toLowerCase().charAt(0);
processSelection(selection);
} while (selection != 'x');
}
private void displayMenu() {
System.out.println("\n **** Ozzey Attraction Menu ****");
System.out.println("A : Add New Attraction");
System.out.println("B : View Attraction");
System.out.println("C : List All Attractions");
System.out.println("D : Sell Ticket");
System.out.println("E : Refund Ticket");
System.out.println("F : Remove Attraction");
System.out.println("X : Exit\n\n");
System.out.printf("Enter selection : ");
}
private void createAttraction() {
String description;
double ticketCost;
char chosen;
int maxGroupSize;
String contactDetails;
int amountActivities;
System.out.print("\nEnter attraction description : ");
description = sc.nextLine();
System.out.print("Enter cost of a Ticket : ");
ticketCost = Double.parseDouble(sc.nextLine());
System.out.println("Is this a supervised tour ? [Y/N] :");
chosen = sc.nextLine().toLowerCase().charAt(0);
switch (chosen) {
case 'y':
System.out.println("What is maximum permitted tour group size?");
maxGroupSize = Integer.parseInt(sc.nextLine());
System.out.println("Enter the agency contact details: ");
contactDetails = sc.nextLine();
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
while (amountActivities < 1) {
System.out.println("Please enter valid number of activities great than zero");
System.out.println("How many activity are there?");
amountActivities = Integer.parseInt(sc.nextLine());
}
String[] storedActivities = new String[amountActivities];
int counter = 0;
while (amountActivities > counter) {
System.out.printf("Please enter activity #%d: ", counter);
storedActivities[counter] = sc.nextLine();
counter++;
}
attractions = new Attraction(chosen, description, ticketCost, maxGroupSize, contactDetails,
amountActivities, storedActivities);
break;
case 'n':
String guide;
String rating;
System.out.printf("Enter the instruction guide:\n");
guide = sc.nextLine();
System.out.printf("Enter the difficulty rating:\n");
rating = sc.nextLine();
attractions = new Attraction(chosen, description, ticketCost, guide, rating);
break;
default:
System.out.print("Please Enter valid answer ");
System.out.println("Is this a supervised tour ? [Y/N] :");
}
}
private void processSelection(char selection) {
switch (selection) {
case 'a':
attractions.recordAttraction();
createAttraction();
break;
case 'b':
System.out.printf("b");
break;
case 'c':
System.out.printf("c");
break;
case 'd':
System.out.printf("d");
break;
case 'e':
System.out.printf("e");
break;
case 'f':
System.out.printf("f");
break;
case 'x':
System.out.println("Good Bye!");
break;
default:
System.out.println("Invalid input, try again\n");
}
}
Hi all i stuck a part of my project for school i have to create a single array in my Attraction class called int[] attractions that can have a max of 5 stored createAttraction() from my stageA class.
When they choose 'a' in my switch statement this were i add createAttraction(); when user has created five attraction in will then tell the user its full and no more can be added. i tried a couple of things but i stuck any help wont be appreciated.
Note: this is the way project has to be setup.
Here are few things you should change in your code :
Change the constructor in attractions class, since you have already set final variable as 5 and if it is fixed, you do not need constructor with parameter: MAX_NUM_ATTRACTIONS
You need to initialise attraction object in StageA class :
private Attraction attractions = null; => private Attraction attractions = new Attraction()
Decide when you want to increment counter variable, when you dorecordAttraction or actually creating one and count should be checked greater or equal to attractions length/ MAX_NUM_ATTRACTIONS
return a value from method record Attraction to decide if you have to proceed with createAttraction or not

Why does my program crash when i excute method "O"?

package trainbooking;
import java.util.Scanner;
public class Trainbooking {
static final int SEATING_CAPACITY = 8;
public static void displayMenu() {
System.out.println("WELCOME TO OUR BOOKING SYSTEM");
System.out.println("A) Add a customer to seat");
System.out.println("V) View all the seats");
System.out.println("E) Display Empty seats");
System.out.println("D) Delete customer from seat");
System.out.println("F) Find the seat for a given customers name");
System.out.println("S) Store program data in to file");
System.out.println("L) Load program data from file");
System.out.println("O) View seats Ordered alphabetically by name");
System.out.println("Q) Exit the application\n");
}
public static void V(String[]seats) {
for (int i = 0; i < seats.length; i++) {
System.out.println(seats[i]);
}
}
public static void A(String[]seats) {
Scanner input = new Scanner(System.in);
System.out.println("What is the name of the customer you want to add? ");
String customerName = input.next();
System.out.println("What seat number do you want this customer to have?");
int seatNumber = input.nextInt();
seats[seatNumber] = customerName;
System.out.println("Thank you, your record was submitted.");
}
public static void E() {
// System.out.println("Empty seats");
//for(int i=0;<seats.length;i++){
// System.out.println("current seat"+ " is ressrved by" + seats[i]);
// }
}
public static void D() {}
public static void F() {}
public static void S() {}
public static void L() {}
public static void O() {
int name;
String temp;
Scanner input = new Scanner(System.in);
System.out.print("Enter all of the pessenger names below; ");
name = input.nextInt();
String names[] = new String[name];
Scanner b1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for (int i = 0; i < name; i++) {
names[i] = b1.nextLine();
}
for (int i = 0; i < name; i++) {
for (int j = i + 1; j < name; j++) {
if (names[i].compareTo(names[j]) > 0) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Following pessenger names have been Sorted in Order:");
for (int i = 0; i < name - 1; i++) {
System.out.print(names[i] + ",");
}
System.out.print(names[name - 1]);
}
}
public static void main(String[]args) {
String[]seats = new String[SEATING_CAPACITY];
Scanner in = new Scanner(System.in);
char choice;
do {
displayMenu();
System.out.println("Enter a choice or press q to quit the application");
choice = in.next().toUpperCase().charAt(0);
switch (choice) {
case 'A':
A(seats);
break;
case 'V':
V(seats);
break;
case 'E':
E();
break;
case 'D':
D();
break;
case 'F':
F();
break;
case 'S':
S();
break;
case 'L':
L();
break;
case 'O':
O();
break;
default:
System.out.println("You have entered the wrong choice. Please try again!");
}
} while ((choice != 'Q'));
System.out.println("Thank you for using our system.");
}
}
You are probably expecting a String/Text input at this function.
But what you do is the following:
You call the function Scanner.nextInt() which tries to read an Integer/Number value from the console.
What you should do instead of input.nextInt() use input.nextLine() and it shouldn't crash anymore.

cannot resolve or is not a field error

I am trying to search an arraylist of objects for an ID code, but I am stuck.
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1:
addTransaction(argList);
break;
case 2:
;// Search Transaction
break;
case 3:
;// Filter Withdraws and Deposits
break;
case 4:
;// Display transactions
break;
case 5:
System.out.println("End");
break;
default:
System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription) ); }
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.argId.get(i).contains(searchId)){
System.out.println("Yes");
}
}
}
}
My second file contains this
public class Transaction {
int id;
char type;
double amount;
String description;
public Transaction(int argId, double argAmount,char argType, String
argDescription){
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public void getId(int id){
}
public void getAmount(double amount){
}
public void getType(char type){
}
public void getDescription(String description){
}
}
And i get the error message: argId cannot be resolved or is not a field on line 58. I think my error is that argId is not part of the ArrayList, and i need to find the right tern to search the ID codes in the ArrayList.
Thanks
Earlier, before you edited your question, you had wrong getter methods.
Instead of
public void getId(int id){
}
you should write this:
public int getId() {
return id;
}
Declare your fields in Transaction class as private.
Then change your other getters in the similar way.
About your actual question, you can use for-each loop:
public static void searchTransactions(ArrayList<Transaction> argList) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for (Transaction transaction : argList) {
if (transaction.getId() == searchId) {
System.out.println("Yes");
break;
}
}
}
}
If you insist for i loop, change it this way:
for (int i = 0; i < argList.size(); i++) {
if(argList.get(i).getId() == searchId){
System.out.println("Yes");
break;
}
}
ArgId is a property of the objects in the list, not a property of the list itself which is why the compiler is giving you an error.
Looks like a typo:
You have:
argList.argId.get(i).contains(searchId)
try using:
argList.get(i).argId.contains(searchId)
argList is a collection, then you get object, read argId and check if it contains searchId
I would suggest to encapsulate class Transaction:
public class Transaction {
private int id;
private char type;
private double amount;
private String description;
public Transaction(int argId, double argAmount, char argType, String argDescription) {
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public int getId() {
return id;
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
Then main class will look in this way:
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1: ; addTransaction(argList);
break;
case 2: ;// Search Transaction
break;
case 3: ;// Filter Withdraws and Deposits
break;
case 4: ;// Display transactions
break;
case 5: System.out.println("End");
break;
default: System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription)
);
}
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.get(i).getId()==searchId){
System.out.println("Yes");
}
}
}
}

Java Constructor & Arrays

I am learning java. This is for a class that I take online. My assignment is finished.
I am trying to figure out the cause for the following.
The two main issues I have are:
1)It seems to be storing only one flower and ignoring the other inputs. How can I correct this?
2) Display flower (e.g Roses - 2):
Immediately after it displays the flowers and their count it will give me the following error message.
Flower Pack:
Daffodils - 1
Roses - 1
Exception in thread "main" java.lang.NullPointerException
at Assignment2.displayFlowers(Assignment2.java:203)
at Assignment2.<init>(Assignment2.java:44)
at Assignment2.main(Assignment2.java:9)
I believe it's origination from this statement
flowerName = searchingPack[i].getName();
Here is my code:
public class Flower {
private String name;
private String color;
private String thorns;
private String smell;
public Flower(){
}
public Flower(String flowerName, String flowerColor, String flowerThorns, String flowerSmell){
name = flowerName;
color = flowerColor;
thorns = flowerThorns;
smell = flowerSmell;
}
public String getName(){
return name;
}
public void setName(String flowerName){
name = flowerName;
}
public String getColor(){
return color;
}
public void setColor(String flowerColor){
color = flowerColor;
}
public String getThorns(){
return thorns;
}
public void setThorns(String flowerThorns){
thorns = flowerThorns;
}
public String getSmell(){
return smell;
}
public void setSmell(String flowerSmell){
smell = flowerSmell;
}
}
import java.util.Scanner;
public class Assignment2 {
public static void main(String[] args){
new Assignment2 ();
}
// This will act as our program switchboard
public Assignment2 (){
Scanner input = new Scanner(System.in);
Flower[] flowerPack = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
System.exit(0);
}
}
}
//ADD FLOWERS
private void addFlower(Flower[] flowerPack) { //This is storing 1 flower but not anything else*********
Scanner add = new Scanner(System.in);
String name,color, thorns, smell;
System.out.println("\nEnter the name of the flower to add: ");
name = add.nextLine();
System.out.println("\nEnter the color of the flower: ");
color = add.nextLine();
System.out.println("\nAre there thorns present: YES or NO ");
thorns = add.nextLine();
System.out.println("\nDoes the flower smell: YES or NO ");
smell = add.nextLine();
boolean flowerInserted = false;
for(int i = 0; i < flowerPack.length; i++){
if(flowerPack[i] == null){
Flower newFlower = new Flower(name, color, thorns, smell);
flowerPack[i] = newFlower;
flowerInserted = true;
break;
}
}
if(flowerInserted){
System.out.println("Flower inserted.");
System.out.println();
}else{
System.out.println("\nFlower pack is full and could not add another flower.\n");
}
}
//REMOVE FLOWERS
private void removeFlower(Flower[] flowerPack) {
Scanner remove = new Scanner(System.in);
String removeName, removeColor;
for(int i = 0; i < flowerPack.length; i++){
System.out.println("\nEnter the name of the flower to remove: ");
removeName = remove.nextLine();
System.out.println("\nEnter the color of the flower: ");
removeColor = remove.nextLine();
if (flowerPack[i] != null)
if (flowerPack[i].getName().equalsIgnoreCase(removeName) && flowerPack[i].getColor().equalsIgnoreCase(removeColor)){
for(int j = i; j < flowerPack.length - 1; j++) {
flowerPack[j] = flowerPack[j + 1];
}
flowerPack[flowerPack.length - 1] = null;
System.out.println("\nFlower removed.\n");
break;
}
else{
System.out.println("\nThat flower was not found.\n");
}
}
}
//SEARCH FOR FLOWERS
private void searchFlowers(Flower[] flowerPack) {
Scanner flowerSearch = new Scanner(System.in);
String name, color, thorns, smell;
int options;
System.out.println("1: Seach by name.");
System.out.println("2: Seach by color.");
System.out.println("3: Seach for flowers with thorns.");
System.out.println("4: Seach for flowers that smell.");
options = flowerSearch.nextInt();
flowerSearch.nextLine();
boolean found = false;
for(int i = 0; i < flowerPack.length; i++){
if(options == 1){
System.out.println("\nEnter the name of the flower: ");
name = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getName().equalsIgnoreCase(name)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options == 2){
System.out.println("\nEnter the color of the flower: ");
color = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getColor().equalsIgnoreCase(color)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options == 3){
System.out.println("\nFlowers with thorns or no thorns: YES or NO ");
thorns = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getThorns().equalsIgnoreCase(thorns)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(options ==4){
System.out.println("\nFlower with aroma or no aroma: YES or NO ");
smell = flowerSearch.nextLine();
if (flowerPack[i] != null) {
if (flowerPack[i].getSmell().equalsIgnoreCase(smell)) {
found = true;
System.out.println("\nFlower was found at index " + i + ".");
break;
}
}
}
if(!found){
System.out.println("\nSorry, no match found.");
}
}
}
//DISPLAY FLOWERS
private void displayFlowers(Flower[] flowerPack) {
System.out.println("Flower Pack: \n");
Flower[] searchingPack = new Flower[flowerPack.length];
for (int i = 0; i < searchingPack.length; i++) {
searchingPack[i] = flowerPack[i];
}
String flowerName = null;
int count = 0;
for(int i = 0; i < searchingPack.length; i++) {
i = 0;
flowerName = searchingPack[i].getName(); // this line is giving me an error!***********************************
if (searchingPack[i].getName() == null || searchingPack[i].getName().equals(null)) {
break;
}
for (int j = 0; j < flowerPack.length; j++) {
if (flowerPack[j] != null) {
if (flowerPack[j].getName().equalsIgnoreCase(flowerName)) {
count++;
}
}
}
for (int k = 0; k < count; k++) {
silentRemove(searchingPack, flowerName);
}
System.out.println(flowerName + " - " + count);
System.out.println();
count = 0;
}
}
private void silentRemove(Flower flowerPack[], String flowerName) {
for (int i = 0; i < flowerPack.length; i++) {
if (flowerPack[i] != null) {
if (flowerPack[i].getName().equalsIgnoreCase(flowerName)) {
for (int j = i; j < flowerPack.length - 1; j++) {
flowerPack[j] = flowerPack[j + 1];
}
flowerPack[flowerPack.length - 1] = null;
break;
}
}
}
}
}
Does it need to be an array? A List<Flower> is more appropriate here. What is happening is you're only adding 2 flowers, but looping over all 25 elements in the array, some of which are still null
The problem is with
flowerName = searchingPack[i].getName();
because searchingPack[i] might be null and then you're trying to reach an address that doesn't exists.
do something like this:
if(searchingPack[i]==null)
flowerName="";
else
flowerName = searchingPack[i].getName();
If you are planning on doing the same kinds of actions you might consider putting an "empty" flower at each index in the array so it won't throw an error.

Unable to continue inputting parameters while looping to create objects for an arraylist

edit: I solved it. The problem was that I was trying to clear the previous value held in the scanner in the wrong spot (needed it outside the if statements). I also cleaned up the continueInput method with a switch variable. I'll post the correct version as an answer.
I'm trying to create objects with a loop and then store them in an arraylist that I'll later print to file. I can create the first object just fine, but on the second iteration through the loop I can't move past entering the cartoon name. I get the prompt for the name, but nothing happens no matter what I enter.
Here's my main class:
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Scanner;
enum CartoonType{FOX,CHICKEN,RABBIT,MOUSE,DOG,CAT,BIRD,FISH,DUCK,RAT,NULL};
public class Main {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<CartoonStar> cartoonStars = new ArrayList<CartoonStar>();
String cartoonName;
CartoonType cartoonType;
String cartoonTypeString;
int popularityIndex;
boolean moreInput;
int counter = 0;
do {
cartoonName = cartoonName(stdin);
cartoonType = cartoonType(stdin);
cartoonTypeString = cartoonType.toString();
popularityIndex = popularityNumber(stdin);
cartoonStars.add(new CartoonStar(cartoonName, cartoonType, popularityIndex));
cartoonStars.get(counter).setName(cartoonName);
cartoonStars.get(counter).setType(cartoonType);
cartoonStars.get(counter).setPopularityIndex(popularityIndex);
moreInput = continueInput(stdin);
if (moreInput) {
counter++;
}
} while (moreInput);
}
public static String cartoonName(Scanner stdin) {
String name;
String name1;
int a = 1;
System.out.print("Please enter the name of the cartoon character: ");
name = stdin.nextLine();
do {
name1 = name;
for (int i = 0; i < name.length(); i++) {
if (!Character.isLetter(name.charAt(i))) {
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
name = stdin.nextLine();
if (name.equalsIgnoreCase("continue")) {
a = 0;
name = name1;
} else {
a = 1;
}
} else {
a = 0;
}
}
} while (a == 1);
return name;
} // end of cartoonName method
public static CartoonType cartoonType(Scanner stdin) {
int cartoonType = 0;
CartoonType cType = CartoonType.valueOf("NULL");
int a;
do {
try {
System.out.print("Please enter a number corresponding to the type of cartoon character below.\n"
+ "1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT\n"
+ "Please enter the type of cartoon character: ");
cartoonType = stdin.nextInt();
while (cartoonType < 1 || cartoonType > 10) {
System.out.print("Sorry, please enter a number from 1 to 10. The corresponding types are:/n"
+ "1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT\n");
cartoonType = stdin.nextInt();
}
a = 0;
} catch (InputMismatchException ex) {
System.out.print("Sorry, please enter only integer values.");
a = 1;
stdin.nextLine(); // drop last input
}
} while (a == 1);
switch (cartoonType) {
case 1:
cType = CartoonType.valueOf("FOX");
break;
case 2:
cType = CartoonType.valueOf("CHICKEN");
break;
case 3:
cType = CartoonType.valueOf("RABBIT");
break;
case 4:
cType = CartoonType.valueOf("MOUSE");
break;
case 5:
cType = CartoonType.valueOf("DOG");
break;
case 6:
cType = CartoonType.valueOf("CAT");
break;
case 7:
cType = CartoonType.valueOf("BIRD");
break;
case 8:
cType = CartoonType.valueOf("FISH");
break;
case 9:
cType = CartoonType.valueOf("DUCK");
break;
case 10:
cType = CartoonType.valueOf("RAT");
break;
}
return cType;
} // end of cartoonType method
public static int popularityNumber(Scanner stdin) {
int popNum = 0;
int a;
do {
try {
System.out.print("Please enter a cartoon popularity number from 1 to 10, with 10 being the highest: ");
popNum = stdin.nextInt();
while (popNum < 1 || popNum > 10) {
System.out.print("Sorry, please enter a value from 1 to 10: ");
popNum = stdin.nextInt();
}
a = 1;
} catch (InputMismatchException ex) {
a = 0;
System.out.print("Sorry, please enter only integer values.");
stdin.next();
}
} while (a == 0);
return popNum;
} // end of popularityNumber method
public static boolean continueInput(Scanner stdin) {
boolean moreInput = false;
int a = 1;
System.out.print("More input? Enter 'yes' for more input, or 'no' to quit: ");
String input = stdin.next();
do {
for (int i = 0; i < input.length(); i++) {
if (!Character.isLetter(input.charAt(i))) {
System.out.println("Please enter only 'yes' or 'no'.");
stdin.next();
a = 1;
} else if (input.equalsIgnoreCase("yes")) {
a = 0;
moreInput = true;
} else if (input.equalsIgnoreCase("no")) {
a = 0;
moreInput = false;
} else {
a = 1;
System.out.print("Please enter only 'yes' or 'no'.");
stdin.next();
}
}
} while (a == 1);
return moreInput;
}
}
And here's my other class:
public class CartoonStar {
private String name;
private CartoonType type; //enum types
private int popularityIndex; //1 to 10 10 being the most popular
public CartoonStar() {
}//end no argument construtor
public CartoonStar(String name,CartoonType type, int popularityIndex) {
setName(name);
setType(type);
setPopularityIndex(popularityIndex);
}//end full constructor
//getters and setters
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setType(CartoonType type) {
this.type = type;
}
public CartoonType getType() {
return type;
}
public void setPopularityIndex(int popularityIndex){
this.popularityIndex = popularityIndex;
}
public int getPopularityIndex(){
return popularityIndex;
}
}//end of class CartoonStar
Here's a sample output for my code:
Please enter the name of the cartoon character: w
Please enter a number corresponding to the type of cartoon character below.
1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,
6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT
Please enter the type of cartoon character: 2
Please enter a cartoon popularity number from 1 to 10, with 10 being the highest: 2
More input? Enter 'yes' for more input, or 'no' to quit: yes
Please enter the name of the cartoon character: w
BUILD STOPPED (total time: 11 seconds)
I stopped the program at this point because it just doesn't let me move past this point. Is the issue with the loop in my main method? I've never made objects without explicitly naming them, so I'm confused as to how to create them and later be able to recall them from my arraylist.
for infinite loop,
you need to assing new value entered by user to input variable in continueInput
like input = stdin.next();
so change it as following
public static boolean continueInput(Scanner stdin) {
boolean moreInput = false;
int a = 1;
System.out.print("More input? Enter 'yes' for more input, or 'no' to quit: ");
String input = stdin.next();
do {
for (int i = 0; i < input.length(); i++) {
if (!Character.isLetter(input.charAt(i))) {
System.out.println("Please enter only 'yes' or 'no'.");
input = stdin.next();
a = 1;
} else if (input.equalsIgnoreCase("yes")) {
a = 0;
moreInput = true;
} else if (input.equalsIgnoreCase("no")) {
a = 0;
moreInput = false;
} else {
a = 1;
System.out.print("Please enter only 'yes' or 'no'.");
input = stdin.next();
}
}
} while (a == 1);
return moreInput;
}
Here's the corrected main class (cartoonstar class is unchanged):
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
ArrayList<CartoonStar> cartoonStars = new ArrayList<CartoonStar>();
String cartoonName;
CartoonType cartoonType;
String cartoonTypeString;
int popularityIndex;
boolean moreInput;
int counter = 0;
do {
cartoonName = cartoonName(stdin);
cartoonType = cartoonType(stdin);
cartoonTypeString = cartoonType.toString();
popularityIndex = popularityNumber(stdin);
cartoonStars.add(new CartoonStar(cartoonName, cartoonType, popularityIndex));
cartoonStars.get(counter).setName(cartoonName);
cartoonStars.get(counter).setType(cartoonType);
cartoonStars.get(counter).setPopularityIndex(popularityIndex);
moreInput = continueInput(stdin);
counter++;
} while (moreInput == true);
} // end of main method
public static String cartoonName(Scanner stdin) {
String name;
String name1;
int a = 1;
System.out.print("Please enter the name of the cartoon character: ");
name = stdin.nextLine();
do {
name1 = name;
for (int i = 0; i < name.length(); i++) {
if (!Character.isLetter(name.charAt(i))) {
System.out.println("Please ensure you've entered the correct name. Re-enter the name or enter 'continue' to proceed: ");
name = stdin.nextLine();
if (name.equalsIgnoreCase("continue")) {
a = 0;
name = name1;
} else {
a = 1;
}
} else {
a = 0;
}
}
} while (a == 1);
return name;
} // end of cartoonName method
public static CartoonType cartoonType(Scanner stdin) {
int cartoonType = 0;
CartoonType cType = CartoonType.valueOf("NULL");
int a;
do {
try {
System.out.print("Please enter a number corresponding to the type of cartoon character below.\n"
+ "1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT\n"
+ "Please enter the type of cartoon character: ");
cartoonType = stdin.nextInt();
while (cartoonType < 1 || cartoonType > 10) {
System.out.print("Sorry, please enter a number from 1 to 10. The corresponding types are:/n"
+ "1 = FOX,2 = CHICKEN,3 = RABBIT,4 = MOUSE,5 = DOG,\n6 = CAT,7 = BIRD,8 = FISH,9 = DUCK,10 = RAT\n");
cartoonType = stdin.nextInt();
}
a = 0;
} catch (InputMismatchException ex) {
System.out.print("Sorry, please enter only integer values.");
a = 1;
stdin.nextLine(); // drop last input
}
} while (a == 1);
switch (cartoonType) {
case 1:
cType = CartoonType.valueOf("FOX");
break;
case 2:
cType = CartoonType.valueOf("CHICKEN");
break;
case 3:
cType = CartoonType.valueOf("RABBIT");
break;
case 4:
cType = CartoonType.valueOf("MOUSE");
break;
case 5:
cType = CartoonType.valueOf("DOG");
break;
case 6:
cType = CartoonType.valueOf("CAT");
break;
case 7:
cType = CartoonType.valueOf("BIRD");
break;
case 8:
cType = CartoonType.valueOf("FISH");
break;
case 9:
cType = CartoonType.valueOf("DUCK");
break;
case 10:
cType = CartoonType.valueOf("RAT");
break;
}
return cType;
} // end of cartoonType method
public static int popularityNumber(Scanner stdin) {
int popNum = 0;
int a;
do {
try {
System.out.print("Please enter a cartoon popularity number from 1 to 10, with 10 being the highest: ");
popNum = stdin.nextInt();
while (popNum < 1 || popNum > 10) {
System.out.print("Sorry, please enter a value from 1 to 10: ");
popNum = stdin.nextInt();
}
a = 1;
} catch (InputMismatchException ex) {
a = 0;
System.out.print("Sorry, please enter only integer values.");
stdin.next();
}
} while (a == 0);
return popNum;
} // end of popularityNumber method
public static boolean continueInput(Scanner stdin) {
boolean moreInput = false;
int a;
System.out.print("More input? Enter 'yes' for more input, or 'no' to quit: ");
String input;
do {
switch (input = stdin.next().toLowerCase()) {
case "yes":
a = 0;
moreInput = true;
break;
case "no":
a = 0;
moreInput = false;
break;
default:
a = 1;
System.out.print("Please enter only 'yes' or 'no'.");
}
stdin.nextLine();
} while (a == 1);
return moreInput;
} // end of continueInput method
}

Categories