D
D
ddssbm2021-10-16 11:33:16
Java
ddssbm, 2021-10-16 11:33:16

How to return the value of a for loop in a method?

Good day gentlemen programmers. While studying java and solving some practical problems, I came across one problem, namely - I have a task that sounds like this: Write a Java program to find the number of integers in the range of two given numbers that are divisible by another number.
Data example:
For example, x = 5, y = 20 and p = 3, find the number of integers in the range x..y that are divisible by p, i.e. {I: x ≤ i ≤ y, i mod p = 0}

Having actually read the problem, I solved it without any problems

for (int i = 5; i <= 20; i++) {
    if (i % 3 == 0) out.println(i);
  }

But as soon as I looked into the solution of the author of the problem, I was a little surprised
public static void main(String[] args){
    int x = 5;
    int y = 20;
    int p = 3;
    System.out.println(result(x,y,p));
   } 		
  public static int result(int x, int y, int p) {	
    if (x%p == 0)
      return( y/p - x/p + 1);
    return(y/p - x/p);
  }

In principle, I understand the logic of the solution, but in my opinion there are too many lines. However, it became interesting for me to try to solve this problem also through a method, only using a for loop. This is where the problem begins, so that I don’t write anything in the body of the method, it doesn’t work, then the IDE writes they say there is no return, then the value is incorrect, etc.
I ask you to suggest a solution to this problem using the for loop through the method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MrideaFur, 2021-10-18
@MrideaFur

If you change the type of the method to void, then, according to the idea, it should work with the cycle without errors.
println in a loop + no-frills method call.
If the question is how to get the results of the loop, then you need an output list. Let's say the loop creates a List and passes it.
And then, through the loop, print all the elements of the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question