Reputation: 193
I’m developing a application that will borrow a car to the user, user can choose from the fleet available. Unfortunately when registration number is typed in and name of the borrower is given, program assigns that person to the first entry in arrayList that has been added. I’m not sure how to get program to assign borrower to the item with given registration number. Can anyone point out the mistake I’m making?
Method that sets borrower:
public void askBorrower(){
boolean loop = false;
while(!loop){
String bName = Console.askString("Borrower's Name: ");
while(bName.isEmpty()){
System.out.println("Borrower's name cannot be empty!");
bName = Console.askString("Borrower's Name: ");
}
while(!bName.matches("[a-zA-Z]+")){
System.out.println("Letters only allowed!");
bName = Console.askString("Borrower's Name: ");
}
setBorrower(bName);
loop = true;
boolean newAvailability = false;
setAvailability(newAvailability);
System.out.println("You have successfully borrowed a car.");
}
}
In main class switch triggering borrowing process:
case 4:
System.out.println("Borrowing a car:");
System.out.println("");
sCar = new StaffCar();
sCar.askRegNo();
sCar = (StaffCar)fleet2.find(sCar.getRegNo());
if(sCar == null){
System.out.println("Car not in the fleet, please try again");
}
else if(sCar.availability == false){
System.out.println("Car is out on loan currently");
}
else{
sCar.askBorrower();
}
break;
and find method:
public StaffCar find(String regNo){
int index = regNo.indexOf(regNo);
if(index == -1){
return null;
}
else{
return fleet2.get(index);
}
}
I would very much appreciate any comments or suggestions.
Upvotes: 1
Views: 52
Reputation: 393856
int index = regNo.indexOf(regNo);
Is searching for the registration number in the registration number String, which will always return 0.
You need to search for the registration number in the List. Since fleet2
is a List<StaffCar>
, you can't use indexOf(regNo)
to locate a car by its registration number. You have to iterate over the List
by yourself.
for (StaffCar car : fleet2) {
if (car.getRegNo().equals(regNo))
return car;
}
return null;
Upvotes: 2
Reputation: 11132
int index = regNo.indexOf(regNo);
this line will always return 0 because you're querying for the index position of a string in the string itself position of 'dog' in 'dog' is always 0.
Assuming you fleet2 is a List, the indexOf
method will only give you the position of the element you're passing as parameter. I.e. indexOf(aStaffCar)
will give you the position of the car while indexOf(aString)
will always gives you -1.
I'd sugest you use a Map<String,StaffCar>
with the String regNo
being the key.
Map<String,StaffCar> fleet2 = ...,
public StaffCar find(String regNo){
//will return null if no entry with key regNo found
return fleet2.get(regNo);
}
Upvotes: 1