我正在尝试创建一个方法 searchMachine() ,它接受一个参数并打印它使用该参数找到的机器编号(数组列表中的索引号)(在本例中是成本)。由于某种原因,这是我的代码,它跳过了总是找不到的条件,即使添加了具有该成本的机器也是如此。另外,我在字段中的 TicketMachine 周围有尖括号,该网站不会显示它。我的第一篇文章对编程来说还很陌生。欢迎任何建议。
public class AutomatedTicketOffice
{
private ArrayList <TicketMachine> newMachine;
public AutomatedTicketOffice()
{
newMachine = new ArrayList<TicketMachine>();
}
public void addTicketMachine(int cost)
{
TicketMachine machine = new TicketMachine(cost);
newMachine.add(machine);
}
public void insertMoney(int machineNumber, int amount)
{
TicketMachine machine = newMachine.get(machineNumber);
machine.insertMoney(amount);
}
public void printTicket()
{
for (TicketMachine machine : newMachine)
{
machine.printTicket();
}
}
public void listTicketMachines()
{ int counter = 1;
int noOfTicketMachines= newMachine.size();
if (counter < noOfTicketMachines)
{
for(TicketMachine machine : newMachine)
{System.out.println("Machine no " + ": "+ counter);
counter++;
}
}
}
public void searchMachine(int cost)
{ int machineIndex= 0;
boolean found = false;
while ( machineIndex < newMachine.size() && !found){
if (newMachine.contains(cost))
{System.out.println("Machine no " + " : " + machineIndex );
found = true;
} else {
machineIndex++;
System.out.println("There is no such Ticket Machine");
}
}
}
}
最佳答案
您必须迭代整个 ArrayList
并手动比较 TicketMachine
。
for (int i = 0; i < newMachine.size(); i++) {
// newMachine is a terrible name for a list, just saying
if (newMachine.get(i).getCost() == cost) {
System.out.println("Machine no: " + i);
found = true;
// break; // depends if you just want to find one or all of them
}
}
if (!found)
System.out.println("There is no such Ticket Machine");
当然,TicketMachine
必须允许访问其参数。
public class TicketMachine {
private int cost;
// other variables
// constructor, i.e.,
public TicketMachine(int cost) {
this.cost = cost;
}
public int getCost() {
return cost;
}
}
如果 cost
是 public
字段,您可以通过 newMachine.get(i).cost
在循环中访问它,而不是使用Getter
访问权限。
编辑:因为你问了。
for (TicketMachine machine : newMachine) {
if (machine.getCost() == cost) {
System.out.println("Machine no: " + newMachine.indexOf(machine));
found = true;
// break; // depends if you just want to find one or all of them
}
}
与上面的循环执行相同的操作。
关于java - 我如何在java中搜索类类型的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35337970/