[英]Get random object from arraylist specific variable
I'm trying to get a random object from an arraylist. 我正在尝试从arraylist获取随机对象。 The random should be among the object in the arraylist having the variable available as true.
随机变量应位于arraylist中具有可用变量为true的对象之间。
Right now it get a random attendant from the whole arraylist. 现在,它从整个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. PS:对不起,我的英语。 It's my 3rd language
这是我的第三种语言
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
告诉我是否有问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.