无限循环。有人有主意吗?

时间:2013-10-31 04:30:57

标签: java

public int sum (int num1, int num2){
    int sum = 0;
        if(num2>num1){
        for (int i = num1; i<=num2; i++){
            sum = sum + i;
            }
        }
        else{
        for (int i = num2; i <= num1; i++){
            sum = sum + i;
            }
        }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum(num1, num2);
    }
}

无限循环问题。任何修复? 试图找到两个输入之间所有数字的总和。这是班级定义的任何想法吗?

3 个答案:

答案 0 :(得分:2)

代替回归sum(num1, num2);你应该return sum;

答案 1 :(得分:0)

public int sum (int num1, int num2)
{
   int sum = 0;
   if(num2>num1)
   {
        for (int i = num1; i<=num2; i++)
        {
            sum = sum + i;
         }
   }
   else
   {
        for (int i = num2; i <= num1; i++)
        {
            sum = sum + i;
        }
    }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum;  
  }

你正在做递归调用问题..

答案 2 :(得分:0)

您正在return sum(num1, num2);递归地调用该函数。因此,将return sum(num1, num2);更改为return sum;