Home > Net >  I cant get the same result as my sample outputs?
I cant get the same result as my sample outputs?

Time:01-02

Task: The fives(int) method prints all 5s that are below the given number below each other. Then the method prints on a new line how many numbers it printed before.

Correct the error(s) in the fives(int) method so that the method works as described above again.

Sample Input 1:

30
Sample Output 1:

5
10
15
20
25
5
Sample Input 2:

5
Sample Output 2:

0
Sample Input 3:

0
Sample Output 3:

0
Sample Input 4:

18
Sample Output 4:

5
10
2
import java.util.Scanner;
public class Main {
    public static void fives(int limit) {
        int i;
        for (i = 1; i <= (limit / 5); i  ) {
            limit = limit - i;
            System.out.println(i * 5);
        }
        System.out.println(i);
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        fives(scanner.nextInt());
    }
}

My Output:

5
10
15
20
5

My Output 2:
1

My output 3:
5
10
15
4

CodePudding user response:

You over complicated a simple task since you know you just want the 5s you can increment the i by 5 and if the given number is a multiple of 5 you know you can ignore it so i < limit and then just count by 1 every passing

public static void fives(int limit) {
            int count = 0;
            for (int i = 5 ; i < limit; i  = 5) {
                System.out.println(i);
                count  ;
            }
            System.out.println(count);
        }

CodePudding user response:

do you know what the % (Mod Operator) is/does. I think it might help you out in this code

  • Related