Reputation: 113
I'm trying to get a random object from an arraylist. The random should be among the object in the arraylist having the variable available as true.
Right now it get a random attendant from the whole arraylist. I just need it to specify a limit to attendants being true(variable) this is the line:
return myAtt.get(randAtt.nextInt(myAtt.size()));
This is the method:
public static Attendant askForAtt() {
Scanner scanAtt = new Scanner(System.in);
Random randAtt = new Random();
//Attendant asnAtt = null;
System.out.println("Do you require an Attendant ? Y or N");
String response = scanAtt.next();
if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y"))) {
// Cars.setAssignedTo(myAtt.get(randAtt.nextInt(myAtt.size())));
return myAtt.get(randAtt.nextInt(myAtt.size()));
} else if ((response.equals("n")) || (response.equals("no")) || (response.equals("No")) || (response.equals("N"))) {
return new Attendant ("User");
}
return new Attendant ("User"); //If input is neither Yes nor No then return new Attendant
}
What am I supposed to type? My attendants are like that:
public Attendant(int staffNum, String id, boolean available, attNm name, Cars assign) {
this.staffNum = staffNum;
this.id = id;
this.available = available;
this.name = name;
this.assign = assign;
}
PS:Sorry for my English. It's my 3rd language
Upvotes: 1
Views: 114
Reputation: 136
On your Attendant class, add this function
public boolean isAvailable(){
return available;
}
Then
public static Attendant askForAtt() {
...
if ((response.equals("y")) || (response.equals("yes")) || (response.equals("Yes")) || (response.equals("Y")) && someoneIsAvailable()) {
ArrayList<Attendant> temp = getAvailableAttendants();
Attendant attendant = temp.get(randAtt.nextInt(temp.size()));
return attendant;
}
...
}
public boolean someoneIsAvailable(){
for(int i = 0; i<myAtt.size(); i++){
if(myAtt.get(i).isAvailable()){
return true;
}
}
return false;
}
public ArrayList<Attendant> getAvailableAttendants(){
ArrayList<Attendant> availableAtt = new ArrayList<>();
for(int i = 0; i<myAtt.size(); i++){
Attendant att = myAtt.get(i)
if(att.isAvailable()){
availableAtt.add(att);
}
}
return availableAtt;
}
Also, you can use
String.equalsIgnoreCase(String);
cause in your trapping the user could do "yEs". Hope that helps. Tell me if something is wrong
Upvotes: 4