我正在尝试使方法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/