Search code examples
javafor-loopmultiplication

Multiply a number by n values in a for loop in Java


I have:

salary = 2000;
n= salary/200 = 10 //number of loops;
contribution = 0.1, 0.2, 0.3, 0.4...;

I need to make a for loop that gets the sum of salary x contribution as:

salary x contribution1 = 500x0.1 salary x contribution2 = 500x0.2 ...etc...

this is a method of my class:


public static double pensionContribution(double salary) {
        
        
    double n = salary/200;
    int n_round = (int) Math.floor(n);
        
    int start = 1;
    List<Integer> n_list = IntStream.rangeClosed(start, n_round)
                .boxed().collect(Collectors.toList());
        
        
    double counter = 0.1;
        
    for (int i = 0; i < n_list.size(); i++) {
           System.out.println(n_list.get((int) (salary*counter)));
                 
    }
        counter = counter + 0.1;
        //need the sum of all values of (salary*counter)
        
    return n_round;
            
    }

Thanks!


Solution

  • you can use this loop:

    for(int i = 0;i < [times to loop];i++){
    
         resultofmultiplication = (salary*counter)
         sum = sum + resultofmultiplication
         counter = counter + 0.1
    
    }
    return sum;
    

    you will get all the results from the multiplications summed. idk why you need a list but this will give you the sum of the multiplications