【问题标题】:Java When I run this method in my code, sometimes it shows full result, other times it doesn't [closed]Java当我在我的代码中运行这个方法时,有时它会显示完整的结果,有时它不会[关闭]
【发布时间】:2015-06-06 04:15:12
【问题描述】:

如果这个函数正在运行:

public static void maximizeweight(int[] weight, int[] A){
        Random r = new Random();
        int random = r.nextInt(A.length);
        for(int i=0;i<A.length;i++){
            while(totalweight(weight,A) < 630){
                if(A[random]==0)
                    A[random] += 1;
            }
        }
    }

输出有时会稍微中断或冻结 eclipse,完全随机,有时它能够给出整个结果,有时它不显示所需结果的最后部分。

【问题讨论】:

  • totalweight(...) 是做什么的?你真的应该先用调试器做一些调试。
  • 很可能是由于方法内部存在无限循环。请显示整个班级,或 totalweight 方法。谢谢!
  • 显然死循环是可能的
  • 如果 A[random] != 0 and totalweight
  • while 循环移到 for 循环之外;)

标签: java function console


【解决方案1】:

如果您的 A[random] != 0 仍然是您的 totalweight() 返回 int random = r.nextInt(A.length); 移动到您的 while 循环中。

public static void maximizeweight(int[] weight, int[] A){
        Random r = new Random();
        for(int i=0;i<A.length;i++){
            while(totalweight(weight,A) < 630){
                int random = r.nextInt(A.length);
                if(A[random]==0)
                    A[random] += 1;
            }
        }
    }

注意:如果weight 数组的总和仍小于 630,这仍会无限循环。因此您需要进行额外检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多