Answer the question
In order to leave comments, you need to log in
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);
}
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);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question