Java 利用结构数据寻找相似生日

Java 利用结构数据寻找相似生日,java,arrays,data-structures,Java,Arrays,Data Structures,嘿,伙计们,我正在尝试获取相同生日的人数,但此解决方案不起作用。此程序显示0.0%。请帮助我 public double calculate(int size, int count) { int matches = 0;//initializing an integer variable boolean out = false; List<Integer> days=new ArrayList<Integer>();// creating arra

嘿,伙计们,我正在尝试获取相同生日的人数,但此解决方案不起作用。此程序显示0.0%。请帮助我

public double calculate(int size, int count) {
    int matches = 0;//initializing an integer variable
    boolean out = false;
    List<Integer> days=new ArrayList<Integer>();// creating arraylist name days  of type int
    for (int j = 0; j <count; j++) {
        for (int i = 0; i < size; i++) {// initializing for loop till less than size
            Random rand = new Random(); // creating an object of random function

            int Brday = rand.nextInt(364) + 0;//initializing the limit of randomc number chozen

            days.add(Brday); //adding values to arraylist
        }

        for (int l = 0; l < size; l++) {
            int temp = l;//assigning value of l to a variable
            for (int k = l + 1; k < size; k++) {
                if (days.get(k) == temp) {// check statement to check values are same

                    matches++;//incrementing variable
                    out = true;
                    mOut.print("Count does have same birthday" + matches);
                    break;

                } else {
                    mOut.print("does not have same birthday");

                }
            }
            if (out) {
                out = false;
                break;
            }

        }
    }
    double prob = (double) matches / count;
    mOut.print("The probability for two students to share a birthday is " + prob*100 + ".");
    return prob;//returning double value of the function
}
public双重计算(整数大小,整数计数){
int matches=0;//初始化整型变量
布尔输出=假;
List days=new ArrayList();//创建int类型的ArrayList name days

对于(intj=0;j实际上,您的代码可以得到0%或100%。如果您想查看,请尝试使用
calculate(100100)
调用它

这段代码有两个错误。首先,如果您多次运行模拟(
count
>1),那么您永远不会在第二次迭代之前清除生日列表

您的方法应以以下内容开始:

public double calculate(int size, int count) {
    int matches = 0;
    boolean out = false;
    List<Integer> days;
    for (int j = 0; j <count; j++) {
        days = new ArrayList<Integer>();
应改为:

int temp = days.get(l); // Remember the birthday at index l

通过这些更改,您将获得更好的结果。

@RC。OP不是将==用于对象,而是将==用于
Integer
int
,这将导致自动取消装箱。@ErwinBolwidt您是对的,我的错。您不能使用吗?非常感谢您的良好响应。它现在正在工作,但需要解决一个问题时间到了。如果你也能给我建议一个解决方案,那将是非常感谢的…@FarasatNiazi我认为你觉得答案很有用。你能对答案进行上投票吗?如果你将鼠标悬停在上投票按钮上,你会在工具提示中看到这意味着“这个答案很有用”请向我推荐耗时较少的解决方案和能够处理较大值的解决方案?
int temp = days.get(l); // Remember the birthday at index l