Home > Back-end >  Java method to get sum of int based on test logic
Java method to get sum of int based on test logic

Time:10-14

I am new to learning java and I have a written a method below. I am trying to understand how to satisfy the tester methods. Is there a way to get the correct logic with the while loop? I stated that the sum = 0 and while the sum is less than i, increment the sum and loop till it reaches i then return the sum (or thats what i think that's what im trying to do) to satisfy the test. When i look at the junit error message for 1) it says its giving me 10 but expects 55, 2) says im getting 49 but expects 1225. 3) is satisfied. What am i doing wrong here? Is it possible to do this method either with an if statement or while loop?

 public int sumOfInts(int i) {
        int sum = 0;
        
        while(sum < i)
             sum;
        return sum;
        
    }
   public void testSumOfInts2() {
                   int sumOfInts = math.sumOfInts(10);
                   assertEquals(55, sumOfInts);

     public void testSumOfInts3() {
                int sumOfInts = math.sumOfInts(49);
                assertEquals(1225, sumOfInts);
     public void testSumOfInts4() {
                int sumOfInts = math.sumOfInts(-49);
                assertEquals(0, sumOfInts);

CodePudding user response:

You are looking to make a method that gives you the cumulative sum. The method you have written just gives you the number of times it runs, which is exactly the number you have provided as argument.

You need to differentiate between the counter (the argument) and the cumulative sum, and also update the value of the counter so that the while loop knows when to exit.

Lastly, the <= comparison is necessary to get the correct value (vs just <).

Here is an example:

   public int sumOfInts(int i) {
        int sum = 0;
        int counter = 0;

        while(counter <= i) {
            sum = sum   counter;
            counter = counter   1;
        }
        return sum;
    }

CodePudding user response:

Try this

public int sumOfInts(int i) {
    int sum = 0;
    int iteration = 0; 
    while(iteration < i){
       sum = sum iteration;
       iteration  ;
    }  
    return sum;
    
}
  • Related