+ Reply to Thread
Results 1 to 3 of 3
  1. Junior Member Haruna Umar Adoga's Avatar
    Join Date
    Jul 2009
    Location
    Hatfield, United Kingdom
    Posts
    22

    Certifications
    ITILv3, CCNA, CCNP, Beng Elect Elect Engineering
    #1

    Default Simple Java method

    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;}}
    Reply With Quote Quote  

  2. SS -->
  3. Security Nut NightShade03's Avatar
    Join Date
    Mar 2009
    Location
    New York
    Posts
    1,379

    Certifications
    RHCSA, JNCIA-Junos, CCNA, CCENT, MCSA (2K3), MCP, Security+, Network+, A+
    #2
    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.
    Reply With Quote Quote  

  4. Junior Member Haruna Umar Adoga's Avatar
    Join Date
    Jul 2009
    Location
    Hatfield, United Kingdom
    Posts
    22

    Certifications
    ITILv3, CCNA, CCNP, Beng Elect Elect Engineering
    #3

    Default thanks @nightshade03

    Thanks for your quick response, the code now works
    Reply With Quote Quote  

+ Reply to Thread

Social Networking & Bookmarks