一个简单的Java方法不起作用

时间:2014-09-23 07:32:08

标签: java methods

大家好我是java编程语言的新手并且一直在学习使用方法,下面是我写的一个简单的方法,用于添加两个数字但是当我运行代码时,它不显示任何输出,请问什么我错了吗?在这种情况下,代码应该将数字从2到4加起来

//testing Java methods
    public class Methods {
       public static void main(String [] args) {
         int addition = add (2,4);
         System.out.println(addition);
      }

//the method for addition
      public static int add(int a, int b){
         int sum = 0;
         for (int i = a; a <= b ; i++)
           sum += i;
        return sum;
    }
}

4 个答案:

答案 0 :(得分:4)

for (int i = a; a <= b ; i++)

应该是

 for (int i = a; i <= b ; i++)

答案 1 :(得分:1)

它实际上遇到了无限循环

尝试此程序(从a <= b to i <= b更改)

 public static void main(String[] args) {
        int addition = add(2, 4);
        System.out.println(addition);
    }

    // the method for addition
    public static int add(int a, int b) {
        int sum = 0;
        for (int i = a ; i <= b ; i++) {
            sum += i;
        }
        return sum;
    }

<强>输出

9

答案 2 :(得分:0)

你的for循环应该是

for (int i = a; i <= b ; i++)

答案 3 :(得分:0)

//testing Java methods
public class Methods {
    public static void main(String[] args) {
        int addition = add(2,4);
        System.out.println(addition);
    }

    //the method for addition
    public int add(int a, int b){ // Place this method in the class.
        int sum = 0;
        for (int i = a; i <= b ; i++){ // "a <= b" Has to be: i <= b
            sum += i;
        }
        return sum;
    }
}

我认为这是你想要的。

结果将是: 2 + 3 + 4 = 9