Options

Simple Java method

Haruna Umar AdogaHaruna Umar Adoga Member Posts: 24 ■□□□□□□□□□
Hello everyone I am a newbie with the java programming language and have been learning the use of methods, below is a simple method i wrote for adding two numbers but when I run the code, it doe not display any output, please what I am doing wrongly? the code should sum numbers from 2 to 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;}}

Comments

  • Options
    NightShade03NightShade03 Member Posts: 1,383 ■■■■■■■□□□
    You problem is in the for loop:

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

    Here you are saying i = a, while a <= b continue to execute this loop, and for each iteration of the loop add 1 to the variable i.

    The problem is that you are confusing variables here. You are incrementing i, but your logic (the middle expression) is testing to see if a is <= b. You need to change this to test if the variable i is <= b. The correct code should be:

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

    Notice the i in the middle logic now? If you run this it will work. I tested your variables of 2, 4 and the output is 9.

    Two additional notes:

    1) Since this is a basic test ensure that you don't have a larger number and then a smaller number or you will run into an infinite loop.

    2) You can troubleshoot issues like this in the future by using a debugger. With your original code I was able to watch the sum variable increase, but never the a variable, which is how I pinpointed your issue. icon_smile.gif
  • Options
    Haruna Umar AdogaHaruna Umar Adoga Member Posts: 24 ■□□□□□□□□□
    Thanks for your quick response, the code now works
Sign In or Register to comment.