Reputation: 11
I got two arrays that i need to compare it they have the same value.
I got one Ticket
class, and a NumberGenerator class.
In the Ticket
class, I got an array that contain my "lucky numbers" and the NumberGenerator
contains the winning numbers.
` public class sammenligning
{ public void jon () { if (Arrays.equals(TicketRegister.getticketReg(),LottoMachine.listOfWinningNumbers())) { System.out.println("We have a winner!"); } } } ` i get an error at the getticketReg (dnw) (ticketReg is the name of the array)
Upvotes: 1
Views: 1000
Reputation: 6158
Ticket class:
public class Ticket {
private Integer [] tickets=new Integer[]{80,35,41};
public Integer[] getTickets() {
return tickets;
}
public void setTickets(Integer[] tickets) {
this.tickets = tickets;
}
}
NumberGenerator:
public class NumberGenerator {
private Integer [] numbers=new Integer[]{51,85,80,35,41};
public Integer[] getNumbers() {
return numbers;
}
public void setNumbers(Integer[] numbers) {
this.numbers = numbers;
}
}
TestClass To comparing:
for(int i=0;i<t.getTickets().length;i++)
{
for(int j=0;j<numberGenerator.getNumbers().length;j++)
{
if(t.getTickets()[i].equals(numberGenerator.getNumbers()[j]))
{
System.out.println("Winner Number is::::"+t.getTickets()[i]);
}
}
}
and if all the elements are same of two arrays then use this
boolean blnResult = Arrays.equals(t.getTickets(),numberGenerator.getNumbers());
Upvotes: 0
Reputation: 22822
Another question you should ask yourself, is where to do that comparison? If you "expose" the lucky numbers from the ticket to the rest of the world (using a public method), you may break encapsulation.
To keep it private and self-contained in Ticket
, maybe you should have a method on your ticket, that goes like:
public boolean isWinningTicket(NumberGenerator numberGenerator) {
// assuming both arrays are sorted
return Arrays.equal(this.luckyNumbers, numberGenerator.getWinningNumbers());
}
Upvotes: 1
Reputation: 2812
You should use Arrays.sort to sort the arrays first, then comparing arrays is trivial with Arrays.equals.
Upvotes: 2
Reputation: 30668
comparing two arrays do not need to be in same class you can compare these using following method
boolean isEqual = Arrays.equals
(array1(ticket class lucky numbers),array2(NumberGenerator winning numbers) );
Upvotes: 0
Reputation: 10239
if (Arrays.equals(aTicket.getNumbers(), aNumberGenerator.getNumbers())) {
System.out.println("We have a winner!");
}
Upvotes: 0