【发布时间】:2021-10-26 17:58:12
【问题描述】:
我有两个类,分别称为 Ticket 和 Register。 Register 是一个接收票证数组的类。工单包含一个时间和一个带有工单 ID 的字符串。我的注册类中的一种方法称为 contains(),它返回一个布尔值。它检查寄存器是否包含具有该 ID 的票证。我的问题是它只对第一个票元素显示为真,而对所有其他票元素显示为假,即使它包含票,因此我相信问题出在我的 contains() 函数上。我对Java非常了解,所以如果有人可以帮助我,将不胜感激。这是我的注册代码和我的驱动程序代码。
/
// This is class called Register that has the methods:"add()","contains()","retrieve()" and the constructor "Register()"
public class Register{
public Ticket[] tickets;
public int numTickets;
public Register(){
tickets = new Ticket[100];
numTickets = 0;
}
public void add(Ticket ticket){ //add ticket method. Takes a ticket as a parameter and adds it to the array
tickets[numTickets] = ticket;
numTickets = numTickets+1; // incramenting array
}
public boolean contains(String ticketID){ //contains method. Takes a string from the ticket using the ID() method and uses as a parameter.
boolean b = false;
for (int i = 0;i<100;i++){
if (ticketID.equals(tickets[i].ID())){ // checks to see if ticket ID is in the array
b = true; // return value is true if found
break;
}
break;
}
return b; // returns true of false
}
public Ticket retrieve(String ticketID){ // returns the ticket with the specified ID
int j = 0; // initializing return value
for (int i = 0;i<100;i++){
if (ticketID.equals(tickets[i].ID())){
j = i;
break;
}
}
return tickets[j]; // returns ticket
}
}
这是我的驱动程序代码
public static void main(String[] args){
Register r = new Register();
Ticket t;
t = new Ticket(new Time("13:00"), "00001");
String ID_One = t.ID();
r.add(t);
t = new Ticket(new Time("13:18"), "00002");
String ID_Two = t.ID();
r.add(t);
System.out.println(r.contains(ID_One));
System.out.println(r.contains("00002"));
System.out.println(r.retrieve(ID_Two).toString());
输出是:
true
false // this should be true
Ticket[id=00002, time=13:18:00]
【问题讨论】:
-
首先,您应该正确缩进您的代码。缩进可以帮助你自己和其他人阅读你的代码。其次,您有两个
break语句。第一个可能属于那里,第二个是无条件执行的,所以循环总是在第一次迭代后退出。
标签: java function class for-loop oop