I have made a program...
in which I scan 3 different strings and then convert them into a single string using toString() then I put that string into array list
for example
"name phonenumber addrees"
it works fine....the problem is when i have to edit it...
i use string.split to split them and edit them...
but i dont know what is wrong..whenever i try to edit it goes to exception error...can anyone help me out?
PROBLEM IN CASE 3 of first switch
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<String> arraylist= new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format="Empty";
int x=1;
int flag=0;
do
{
try
{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice=Integer.parseInt(input.next());
switch (choice)
{
case 1:
{
System.out.println("Enter name ");
name=input.next();
System.out.println("Enter phone number");
phoneNumber=input.next();
System.out.println("Enter address");
address=input.next();
format=FormatObject.toString(phoneNumber, name, address); // will merge these 3 Strings with space in between
arraylist.add(format);
flag++;
}
break;
case 2:
{
System.out.println("Name Phone number Address");
System.out.println();
for(int i=0;i<flag;i++)
{
System.out.println(arraylist.get(i)); //arraylist cant be displayed on nextline without loop
}
}
break;
case 3:
{
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2=input.nextInt();
String dupFormat= arraylist.get(choice2-1);
String[] splitString= dupFormat.split(" ");
switch (choice2)
{
case 1:
{ System.out.println("Enter new name");
splitString[0]=input.next();
break;
}
case 2:
{ System.out.println("Enter new phone number");
splitString[1]=input.next();
}
break;
case 3:
{ System.out.println("Enter new Address");
splitString[2]=input.next();
}
break;
default:
{
System.out.println("Choice is only 1,2,3 ");
}
String newFormat=splitString.toString();
arraylist.add(choice2-1, newFormat);
}
}break;
default:
System.out.println("Error");
break;
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice ..");
}
}while(x==1);
}}
my toString method--->
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public String toString(){
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
public String toString (String phone,String name,String address){
phoneNumber=phone;
nameUser=name;
addressUser=address;
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
}
You have break; statement outside of your second switch cases. For example you have break; outside of
case 2:
{ System.out.println("Enter new phone number");
splitString[1]=input.next();
}
break;
And it will break first switch.
So new string won't add into array. And even if you call this
String newFormat=splitString.toString();
arraylist.add(choice2-1, newFormat);
it will change your data to somthing like [Ljava.lang.String;#1f7030a6. It's because you trying to call toString() on newly created array from dupFormat.split(" ").
I'd recomended change case 3 section to
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2 = input.nextInt();
String dupFormat = arraylist.get(choice2 - 1);
String[] splitString = dupFormat.split(" ");
switch (choice2) {
case 1: {
System.out.println("Enter new name");
FormatObject.nameUser = input.next();
break;
}
case 2: {
System.out.println("Enter new phone number");
FormatObject.phoneNumber = input.next();
break;
}
case 3: {
System.out.println("Enter new Address");
FormatObject.addressUser = input.next();
break;
}
default: {
System.out.println("Choice is only 1,2,3 ");
}
}
String newFormat = FormatObject.toString();
arraylist.add(choice2 - 1, newFormat);
break;
And you will change state of your object and after that you can call toString() again with new data.
couldn't find the issue but your code is very hard to read..
Why would you want to store the Name, Phone number and Address as a String?
I would suggest:
creating a class that contains those fields.
create a function that will implement the code you have in each case (that way you can also test each function seperatly)
in the functions work with an instance of the class from (1) and convert to string only when you want to print.
I would also get read of the do-while, switch but that is up to you
also try to give more meaningful names when you code.. your flag for example is used as a count and not a flag.
so you should do something like this: (and test every function individually)
private List<PersonalData> list = new ArrayList<>();
///....
switch(choise){
case 1://consider replacing with enum
{
list.add(getPersonalDataFromInput());
break;
}
case 2:
{
printAll();
break;
}
case 3:
{
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2=input.nextInt();
String dupFormat= arraylist.get(choice2-1);
if(choice2==1){
list.get(list.size()-1).setName(input.next());
}
else if(choice2==2){
list.get(list.size()-1).setPhone(input.next());
}
else (choice2==3){
list.get(list.size()-1).setAddress(input.next());
}
}
}
}
and the class to create:
class PersonalData{
private String phoneNumber;
private String name;
private String address;
//getters and setters
}
The problem in this code was the choice object..
Because if the input is a wrong input,choice object stays like that forever
that's there should be two objects for the input
Related
I need to remove an element from an ArrayList, based on the user input. So what I have is an ArrayList where a user can register dogs. Then if the user wants to remove a dog, he/she should be able to do it by using the command "remove dog" followed by the name of the dog.
I have tried using an iterator, but when using it only the else statement is used and "Nothing has happened" is printed out on the screen.
import java.util.Iterator;
import java.util.Scanner;
import java.util.ArrayList;
public class DogRegister {
ArrayList<Dog> dogs = new ArrayList<>();
private Scanner keyboard = new Scanner(System.in);
public static void initialize() {
System.out.println("Welcome to this dog application");
}
private boolean handleCommand(String command) {
switch (command) {
case "One":
return true;
case "register new dog":
registerNewDog();
break;
case "increase age":
increaseAge();
break;
case "list dogs":
listDogs();
break;
case "remove dog":
removeDog();
break;
default:
System.out.println("Error: Unknown command");
}
return false;
}
private void registerNewDog() {
System.out.print("What is the dog's name? ");
String dogNameQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("Which breed does it belong to? ");
String dogBreedQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("How old is the dog? ");
int dogAgeQuestion = keyboard.nextInt();
System.out.print("What is its weight? ");
int dogWeightQuestion = keyboard.nextInt();
keyboard.nextLine();
Dog d = new Dog(dogNameQuestion, dogBreedQuestion, dogAgeQuestion,
dogWeightQuestion);
dogs.add(d);
System.out.println(dogs.get(0).toString());
}
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();
dogsIterator.hasNext();) {
if (removeDogList.equals(dogsIterator)) {
System.out.println("The dog has been removed ");
break;
} else {
System.out.println("Nothing has happened ");
break;
}
}
}
public void closeDown() {
System.out.println("Goodbye!");
}
public void run() {
initialize();
runCommandLoop();
}
public static void main(String[] args) {
new DogRegister().run();
}
}
You compare a String will an Iterator as said by JB Nizet :
if (removeDogList.equals(dogsIterator)) {
It will never return true.
Besides even invoking next() on the iterator will not solve the problem as a String cannot be equal to a Dog object either.
Instead of, compare String with String when you use equals() and invoke Iterator.remove() to effectively remove the current iterated element.
That should be fine :
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();dogsIterator.hasNext();) {
Dog dog = dogsIterator.next();
if (removeDogList.equals(dog.getName())) {
dogsIterator.remove();
System.out.println("The dog has been removed");
return;
}
}
System.out.println("Nothing has been removed");
}
An Iterator<Dog> can't possibly be equal to a String: they don't even have the same type.
Only a String can be equal to a String.
You want to get the next value of the iterator, which is a Dog. Then you want to compare the name of the dog with the String input.
And then you want to remove the dog, using the iterator's remove() method. Read the javadoc of Iterator.
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
In my program, I want to transfer credits between two person. All of the info I have added in the arrayList. Each person is given an ID.
To make transaction, user have to enter ID.
The withdraw amount enterd by the user must be subtracted from the particular account and eventually that amount must be added with another particular account, depending on the ID chosen by user. How to do that?
Basically, I don't know how to check the amount/credit with the matching ID, and then performing arithmetic task within that specific person's amount.
Actually the part I am concentrating on is switch (option2) in my code.
This is my code I am working on.
AboutPerson:
public static void main(String[] args) {
String name;
int id;
int option1;
int option2;
double credit;
int withdraw_id;
double withdraw_amount;
double dep_id;
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "3. Transfer credits\n"//need help here
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
case 3:
//transfer credit
System.out.println("To transfer credit between two persons enter 1");//working with this one
System.out.println("To transfer credit within the same persons enter 2");//not focusing on that now
option2 = input.nextInt();
input.nextLine();
switch (option2) {
case 1:
System.out.println("Enter the ID of the person you want to withdraw amount from: ");
withdraw_id = input.nextInt();
System.out.println("Enter withdraw amount: ");
withdraw_amount = input.nextDouble();
//subtract that credit from that account
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
//the amount has been withdrawn will be deposited
//add that credit
System.out.println("Done!\tTo print them out out choose option 2");
break;
}
}
}
}
PersonInfo:
package aboutperson;
public class PersonInfo {
private String name;
private int id;
private double credit;
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}
public void setCredit(double credit) {
this.credit = credit;
}
#Override
public String toString() {
return name + "\t\t" + id + "\t\t" + credit;
}
}
First add getCredit and getID methods to PersonInfo:
public double getCredit() {
return this.credit;
}
public int getID() {
return this.id;
}
And then simply exchange it between the two accounts:
System.out.println("Enter the ID of the person you want to deposit into: ");
dep_id = input.nextDouble();
input.nextLine();
System.out.println("Enter your ID: ");
withdraw_id = input.nextDouble();
input.nextLine();
System.out.println(": ");
withdraw_amount = input.nextDouble();
input.nextLine();
PersonInfo fromPerson = null;
PersonInfo toPerson = null;
//find PersonInfo objects from list:
for (PersonInfo pi : info) {
if (pi.getID() == dep_id) {
toPerson = pi;
break;
}
}
for (PersonInfo pi : info) {
if (pi.getID() == withdraw_id) {
fromPerson = pi;
break;
}
}
if (fromPerson == null || toPerson == null) {
System.out.println("Wrong IDs."); //maybe do something more user friendly here
break;
}
if (withdraw_amount > fromPerson.getCredit()) {
System.out.println("notify of error");
break;
}
fromPerson.setCredit(fromPerson.getCredit() - withdraw_amount);
toPerson.setCredit(toPerson.getCredit() + withdraw_amount);
System.out.println("Done!\tTo print them out out choose option 2");
Instead of storing PersonInfo in List, use Map where you can use key as id and value as PersonInfo itself. so it will be like:
Map<Integer, PersonInfo> info = new HashMap<Integer, PersonInfo>();
...
personInfo.setCredit(input.nextDouble());
perdonIdInfoMap.put(personInfo.getId(), personInfo);
Then when you have two id's get the info from map like:
personInfoFrom = perdonIdInfoMap.get(id1);
personInfoTo = perdonIdInfoMap.get(id2);
//now deduct from one and add to other like personInfoFrom.setCredit(personInfoFrom.getCridit() + personInfoTo.getCredit());
You can iterate over the list and check:
for(PersonInfo person: info){
if(person.getId().equals(searchedId)){
/* here you can do operation on that person*/
/* Printing the balance */
System.out.println("Balance: " + person.getCredit());
/* Adding or subtracting money*/
person.setCredit(person.getCredit() + ammount);
/* Other stuff*/
}
}
Or you could use a Map as SMA suggested
hey i am trying to take inputs from user one by one but its appears to take wrong input... it actually skip the one input to be taken from user ..
e.g..in the code below i want to take name first then address and at last contact but when i do so it skip the name input...
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
int value = 0;
ArrayList<Data> Contacts = new ArrayList<Data>();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter 1 to add a Contact :: Enter 2 to View all Contact");
value = input.nextInt();
switch(value){
case 1:
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
Data objt1 = new Data(name, address, contact);
Contacts.add(objt1);
break;
case 2:
System.out.println("Name\t\tContact\t\tAddress");
for(int i=0; i<Contacts.size(); i++)
{
System.out.println(Contacts.get(i));
}
break;
default:
System.out.println("Sorry wrong input");
}
}
}
}
the data class is here
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public String toString()
{
return String.format("%s\t\t%s\t\t%s", name, cell, address);
}
}
try adding input.nextLine(); after getting the value, this will consume the new line character
value = input.nextInt();
input.nextLine();
(or)
int value = Integer.parseInt(input.nextLine());
I'm getting a NullPointerException at:
If(bookingList.size() == 0)
,
bookingList.add(vehicleBooking)
and
bookingList.add(rvBooking)
And i am not sure what is causing it. Any help is much appreciated.
Stack trace
bookingSystem.FerryBookingSystem at localhost:59034
Thread [main] (Suspended (exception NullPointerException))
FerryBookingSystem.bookingIDExists(String) line: 35
FerryBookingSystem.addVehicleBooking() line: 49
FerryBookingSystem.main(String[]) line: 114
C:\Program Files\Java\jre7\bin\javaw.exe (14/05/2013 10:52:02 PM)
BookingException
package bookingSystem;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
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
public class FerryBookingSystem {
private static ArrayList<VehicleBooking> bookingList;
private static Scanner userInput = new Scanner (System.in);
public FerryBookingSystem(){
bookingList = new ArrayList<VehicleBooking>();
}
public static int bookingIDExists(String IDs){
if (bookingList.size() == 0)
return -1;
for (int i = 0; i < bookingList.size(); i++){
if(bookingList.get(i).getbookingID().equals(IDs))
return i;
}
return -1;
}
public static boolean addVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
if(bookingIDExists(booking_ID) != 1)
{
System.out.println("\nError - Sale ID \"" + booking_ID +
"\" already exists in the system!");
return false;
}
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicle " +
"description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
VehicleBooking vehicleBooking = new VehicleBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(vehicleBooking);
System.out.println("New vehicle booking added successfully for " + booking_ID);
return true;
}
public static boolean addRecreationalVehicleBooking(){
System.out.print("Please enter the booking ID: ");
String booking_ID = userInput.nextLine();
System.out.print("Please enter the registration number for the vehicle: ");
String registration_Number = userInput.nextLine();
System.out.print("Please enter the vehicl description: ");
String vehicle_Description = userInput.nextLine();
System.out.print("Please enter the number of people travelling in the vehicle: ");
int travelling_Number = userInput.nextInt();
userInput.nextLine();
RVBooking rvBooking = new RVBooking(booking_ID, registration_Number, vehicle_Description, travelling_Number);
bookingList.add(rvBooking);
System.out.println("New rvbooking added successfully for " + booking_ID);
return true;
}
public static void displayBookingSummary(){
if (bookingList.size() != 0){
System.out.println("\nSummary of all past vehicle booking stored on system.");
for (int i=0 ; i<bookingList.size() ; i++){
bookingList.get(i).printBookingSummary();
System.out.println("");
}
}
}
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':
break;
case 'E':
break;
case 'F':
break;
case 'X':
break;
default:
break;
}
}
}while(user!='X');
}
}
Your code at:
private static ArrayList<VehicleBooking> bookingList;
have not been initialized. So initialize it.
bookingList is a static attribute of FerryBookingSystem.
You initialize it in the constructor, which is a non-sense for a static attribute.
Then, you never call your constructor because you never instantiate FerryBookingSystem.
Edit:
After looking more deeply into your code, it seems that you first declared bookingList as static then marked all methods static to solve compilations problems...
I don't think that you really need this attribute to be static so just remove the static keywork on your attribute and on all your methods:
public class FerryBookingSystem {
private ArrayList<VehicleBooking> bookingList;
Then, instantiate a FerryBookingSystem at the beginning of your main method:
public static void main (String [] args) throws IOException{
char user;
FerryBookingSystem fbs=new FerryBookingSystem();
and call methods of this instance :
switch (user){
case 'A':
fbs.addVehicleBooking();
break;
case 'B':
fbs.addRecreationalVehicleBooking();
break;
case 'C':
fbs.displayBookingSummary();
Move initialization of the bookingList from a regular constructor to a static initialization block:
static {
bookingList = new ArrayList<VehicleBooking>();
}
or initialize it at the point of declaration:
private static ArrayList<VehicleBooking> bookingList = new ArrayList<VehicleBooking>();
Otherwise, bookingList would remain null until the first call of FerryBookingSystem's constructor is made.
You're initializing the static field bookingList in a constructor and use it in static methods. Now you can call those methods without haveing created an instance of that class.
So there is a good chance, that bookingList is not initialized at the time you call the methods. Either remove all static modifiers or initialize the field directly and drop the constructor.
(I recommend removing all static modifiers and use instances of your class)
Don't initialize the static variables in a constructor. static can be called even before instance created for that class.
In your case bookingList is a static and it can be called without creating any object for this class. My be this is the reason for NullPonterException.