Sean Mcavoy :
I am making a ticket system. If the user is searching for a ticket they type in the name. It is not working when i ask the user to type it in.
If I call the method like this: G1.displayTicket("John Blogs", LottoTickets);
it does work!
Displaying a certain ticket:
System.out.print("\nDo you wish to search for a particular ticket? ");
String certainTicketQ = in.next();
if(certainTicketQ.equalsIgnoreCase("Yes"))
{
System.out.print("Name of the person you wish to search for: ");
String name = in.next();
G1.displayTicket(name, LottoTickets);
}
The method is:
public void displayTicket(String name,Ticket[] LottoTickets)
{
for(int i = 0; i<LottoTickets.length;i++)
{
if(name.equalsIgnoreCase(LottoTickets[i].getName())){
System.out.println(LottoTickets[i]);
break; //Breaks out of loop once ticket is found
}else break;
}
}
Arvind Kumar Avinash :
The problem is due to the presence of else break;
which is breaking the loop in the first iteration itself if LottoTickets[0]
is not equal to name
. It will return the correct result only when LottoTickets[0]
is equal to name
.
public void displayTicket(String name,Ticket[] LottoTickets) {
for(int i = 0; i<LottoTickets.length;i++) {
if(name.equalsIgnoreCase(LottoTickets[i].getName())) {
System.out.println(LottoTickets[i]);
break; //Breaks out of loop once ticket is found
}else break;
}
}
Just remove it and your method will work as intended i.e. it should be:
public void displayTicket(String name,Ticket[] LottoTickets) {
for(int i = 0; i<LottoTickets.length;i++) {
if(name.equalsIgnoreCase(LottoTickets[i].getName())) {
System.out.println(LottoTickets[i]);
break; //Breaks out of loop once ticket is found
}
}
}
Feel free to comment in case of any doubt/issue.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=370891&siteId=1