首页 > 解决方案 > 在输入元素的重量和利润时陷入无限循环

问题描述

在输入权重和利润处陷入无限循环无论您输入多少输出,都不会向前移动任何帮助将不胜感激这是以下代码

import java.util.*;
import java.text.*;

class fracknapsack
{
public static void main(String args[])
{
    Scanner sc = new Scanner(System.in);
    DecimalFormat df = new DecimalFormat("##.##");
    System.out.println("Enter number of elements: ");
    int n = sc.nextInt();
    System.out.println("Enter total mass: ");
    float m = sc.nextFloat();
    System.out.println("Enter weight and profit of "+n+" elements: ");
    float w[] = new float[n];
    float p[] = new float[n];
    float r[] = new float[n];
    float f[] = new float[n];
    float max = (float)0;
    int flag = 0;
    //for(int i=0; i<n; i++)
    //{
    //    int a = sc.nextInt();
    //    w[i] = (float)a;
    //}
    //for(int i=0; i<n; i++)
    //{
    //    int b = sc.nextInt();
    //    p[i] = (float)b;
    //}
    
    for(int i=0; i<=n; i++)
    {
        int a = sc.nextInt();
        int b = sc.nextInt();
        w[i] = (float)a;
        p[i] = (float)b;
        r[i] = p[i]/w[i];
        f[i] = (float)0;
        if(p[i]>max)
        {
            max = p[i];
            flag = i;
        }
    }
     
    float tprofit = (float)0;
    while(m>0)
    {
        if(m>max)
        {
            tprofit = tprofit + p[flag];
            f[flag] = (float)1;
            m = m - max;
        }
        else
        {
            float fraction = max/m;
            tprofit = tprofit + p[flag]*fraction;
            f[flag] = fraction;
            max = 0;
        }
        float j = (float)0;
        for(int i=0; i<n; i++)
        {
            if(j>r[i] && j<max)
            {
                j = r[i];
                flag = i;
            }
        }
        max = j;
    }
    
    System.out.println();
    System.out.println();
    System.out.println("Fraction of weights included: ");
    System.out.println("Weights \t|\t Fraction");
    for(int i=0; i<n; i++)
    {
        System.out.println(df.format(w[i])+"\t|\t"+df.format(f[i]));
    }
    System.out.println();
    System.out.println("Total Profit = "+df.format(tprofit));
}}

我相信这应该可以正常运行,但不是。很困惑可能是什么问题。包括另一个仅用于测试的 for 循环,问题仍然存在。

标签: javaeclipseoutputinfiniteknapsack-problem

解决方案


在第 32 行(第一个循环)中,您过于频繁地迭代一个条目。您想填充数组中的所有 n 个条目 - 但是当从 i=0 迭代到 i<=n 时,您正在填充 n+1

因此,当我尝试您的代码时,我得到了一个 ArrayIndexOutOfBoundsException。

我修复了这个问题,但导致了无限循环,因为“max”变量始终保持为 0,而 m 永远不会改变(始终保持大于 0)。

作为一般提示,您应该用更多的名称命名变量并注释代码。


推荐阅读