Reputation: 115
This is my second day on Java. I came across an interesting question on the Birthday Paradox.
However, I am stuck on how to create a 'Room' with 'persons' and then comparing the persons' birthdays.
Does anyone know how to do this?
Thank you for your effort and time! :)
class Person {
int age;
}
class Room {
int Person;
}
public class BirthdayParadox {
public static void main(String[] args) {
int x = (int) (Math.random() * 364);
int y = (int) (Math.random() * 364);
long r = Math.round(x);
long s = Math.round(y);
Person person1 = new Person();
person1.age = (int) r;
Person person2 = new Person();
person2.age = (int) s;
if (person1.age == person2.age) {
System.out.println("Same!");
}
else if (person1.age != person2.age) {
System.out.println(person1.age + " " + person2.age);
}
}
}
Upvotes: 1
Views: 1238
Reputation: 5647
For this, all you would need is an array of integers, with each index holding the birthday of one person.
For example, to hold the birthdays of 10 people, you would create an integer array of size 10.
int[] birthdays = new int[10];
You can the assign a value to an index of the array with the following:
birthdays[2] = (int)(Math.random() * 364);
The above code would assign the 3rd person's birthday to a random value.
To get the birthday of a person, use similar code to the following:
birthdays[1]
So, to print the 5th person's birthday, you would use
System.out.println(birthdays[4]);
Remember that arrays are 0-indexed, which means that the first value is 0 and the last is (size - 1). So for example, the 6th element is at index 5.
Upvotes: -1
Reputation: 394156
Your Room
class should probably contain a List<Person>
or an array of Person (Person[]).
The constructor of Person
should accept a dateOfBirth
parameter, or, to make it more simple, you can accept an integer between 1 and 365 which represents the date of the birthday not including the year, since that's all you care about. Don't call that member age
, since it has nothing to do with age.
You want to use (int)(Math.random() * 365) + 1
, which would give you integers between 1 and 365. You don't need to use Math.round()
.
Upvotes: 2