从arraylist特定变量获取随机对象 [英] Get random object from arraylist specific variable
问题描述
我正在尝试从arraylist中获取随机对象.随机变量应位于具有可用变量true的arraylist对象中.
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.
现在,它从整个arraylist中获得了一个随机的服务员.我只需要它来指定服务员的真实限制(变量) 这是一行:
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()));
这是方法:
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:对不起,我的英语.这是我的第三语言
PS:Sorry for my English. It's my 3rd language
推荐答案
在您的话务员类中,添加此功能
On your Attendant class, add this function
public boolean isAvailable(){
return available;
}
然后
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;
}
还可以使用
String.equalsIgnoreCase(String);
因为您被诱捕,用户可能会执行是".希望能有所帮助.告诉我是否有问题
cause in your trapping the user could do "yEs". Hope that helps. Tell me if something is wrong
这篇关于从arraylist特定变量获取随机对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!